Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# double.ToString() max number of digits and trailing zeros

Tags:

string

c#

format

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()?

like image 750
Sylvain B. Avatar asked Oct 22 '15 11:10

Sylvain B.


1 Answers

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.

like image 180
Luaan Avatar answered Oct 20 '22 10:10

Luaan