Search code examples
c#floating-pointtostring

How to get floats value without including exponential notation


In C#, is it possible to perform ToString on a float and get the value without using exponentials?

For example, consider the following:

float dummy;

dummy = 0.000006F;

Console.WriteLine(dummy.ToString());

This gives the output

6E-06

However, what I was is

0.000006

The closest I could find was using the "F" qualifier, however I then need to specify the number of decimal places otherwise the value get rounded.

Is there actually a way of doing this automatically or do I need to do a load of funky logic to either trim zeroes or figure out the number of required decimals.

Thanks;
Richard Moss


Solution

  • Try this

    Console.WriteLine(dummy.ToString("F"));
    

    You can also specify number of decimal places. For example F5, F3, etc.

    Also, you can check custom format specifier

    Console.WriteLine(dummy.ToString("0.#########"));