I have some fields returned by a collection as
2.4200
2.0044
2.0000
I want results like
2.42
2.0044
2
I tried with String.Format
, but it returns 2.0000
and setting it to N0
rounds the other values as well.
I have some fields returned by a collection as
2.4200
2.0044
2.0000
I want results like
2.42
2.0044
2
I tried with String.Format
, but it returns 2.0000
and setting it to N0
rounds the other values as well.
Is it not as simple as this, if the input IS a string? You can use one of these:
This should work for all input.
Update Check out the Standard Numeric Formats I've had to explicitly set the precision specifier to 29 as the docs clearly state:
Update Konrad pointed out in the comments:
try like this
and then convert that to float
I ran into the same problem but in a case where I do not have control of the output to string, which was taken care of by a library. After looking into details in the implementation of the Decimal type (see http://msdn.microsoft.com/en-us/library/system.decimal.getbits.aspx), I came up with a neat trick (here as an extension method):
The exponent part of the decimal is reduced to just what is needed. Calling ToString() on the output decimal will write the number without any trailing 0. E.g.
This does exactly what you want:
If your initial value is
decimal
:If your initial value is
string
:And should cost minimum performance.
A very low level approach, but I belive this would be the most performant way by only using fast integer calculations (and no slow string parsing and culture sensitive methods):
Use the hash (
#
) symbol to only display trailing 0's when necessary. See the tests below.