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

How to convert a double to string with 6 maximum 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 string.Format("{0:G6"}, value) zeros and string.Format("{0:G6"}, value) will not match the second example.

Is it possible to use value.ToString("0.######) ?

Is there an equivalent way to do with string.Format() ?

+5
source share
1 answer

You can use value.ToString("0.######") . However, you should consider something else: double not a decimal (base 10) number. You do not have to rely on the decimal notation of a number to be reasonable - a lot of normal decimal bases of 10 numbers require infinite decimal expansion in base 2.

If you care about the decimal representation, it is better to use decimal instead - this is also a floating point number, but in the base 10.

And in any case, this involves rounding - it may or may not be what you want.

+6
source

Source: https://habr.com/ru/post/1234263/


All Articles