How to convert a double
into a string
with 6 max number of digits and remove trailing zeros?
I want to have :
2.123456123 -> "2.123456"
0.0000012 -> "0.000001" (and not "1.2e-6")
12.45 -> "12.45" (and not "12.450000")
36 -> "36" (and not "36.000000")
using string.Format("{0:F6"}, value)
output trailing zeros and string.Format("{0:G6"}, value)
will not fit the second example.
Is it ok to use value.ToString("0.######)
?
Is there an equivalent way to do with string.Format()
?
It is okay to use value.ToString("0.######")
. However, you should consider another thing: double
is not a decimal (base 10) number. You should not rely on the decimal representation of the number to be anything reasonable - plenty of normal decimal base 10 numbers require infinite decimal expansion in base 2.
If you do care about the decimal representation, it might be a better idea to use decimal
instead - it's also a floating point number, but in base 10.
And in either case, this involves rounding - that might or might not be what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With