From a XML file I receive decimals on the format:
1.132000
6.000000
Currently I am using Decimal.Parse like this:
decimal myDecimal = Decimal.Parse(node.Element("myElementName").Value, System.Globalization.CultureInfo.InvariantCulture);
How do print myDecimal to string to look like below ?
1.132 6
If you only need to do this for display then how about using a custom format string?
This will remove all the trailing zeros from the decimal and then you can just use
ToString()
.Or alternatively, if you want an exact amount of precision, say 5 decimal places, first Normalize() and then multiply by 1.00000m.
This meets the example given but POORLY. (I THINK)
What other requirements are there? Are you going to manipulate the values and show the manipulated values to this number of decimals?
Alternate answer involves recursiveness, like so:
And if you wanted an extension method, then this is an option
Added
input.Contains( "." ) &&
per comment from Jon Skeet, but bear in mind this is going to make this incredibly slow. If you know that you'll always have a decimal and no case likemyDecimal = 6000;
then you could drop that test, or you could make this into a class and have several private methods based on whether the input contained a decimal, etc. I was going for simplest and "it works" instead ofEnterprise FizzBuzz
I don't think there are any standard numeric format strings which will always omit trailing insignificant zeroes, I'm afraid.
You could try to write your own decimal normalization method, but it could be quite tricky. With the
BigInteger
class from .NET 4 it would be reasonably feasible, but without that (or something similar) it would be very hard indeed.EDIT: Okay, I think this is what you want:
What about using toString("G29") on your decimal? this does exactly what you're trying to achieve !