How to get floats value without including exponential notation

∥☆過路亽.° 提交于 2019-12-18 14:55:35

问题


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


回答1:


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.#########"));



回答2:


string dum = string.Format("{0:f99}",dummy).TrimEnd('0');
if (dum.EndsWith(",")) dum = dum.Remove(dum.Length - 1);



回答3:


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.




回答4:


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

where 5 its number of decimal places




回答5:


float dummy = 0.000006F;
Console.WriteLine(dummy.ToString("0." + new string('#', 60)));

If you'll be doing this a lot then it makes sense to store the format string in a static field/property somewhere and re-use it, rather than constructing a new string every time:

private static readonly string _allFloatDigits = "0." + new string('#', 60);

// ...

float dummy = 0.000006F;
Console.WriteLine(dummy.ToString(_allFloatDigits));


来源:https://stackoverflow.com/questions/3757945/how-to-get-floats-value-without-including-exponential-notation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!