Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 216
Richard Moss Avatar asked Sep 21 '10 06:09

Richard Moss


3 Answers

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.#########"));
like image 194
default locale Avatar answered Nov 19 '22 18:11

default locale


string dum = string.Format("{0:f99}",dummy).TrimEnd('0');
if (dum.EndsWith(",")) dum = dum.Remove(dum.Length - 1);
like image 3
nan Avatar answered Nov 19 '22 18:11

nan


Without some further background info, it's hard to tell - but it sounds like you want decimal semantics. So why not use the decimal type instead?

decimal dummy;
dummy = 0.000006M;

The decimal type is more accurate at representing decimal numbers than float or double, but it is not as performant. See here for more info.

like image 2
Winston Smith Avatar answered Nov 19 '22 19:11

Winston Smith