How to get floats value without including exponential notation

后端 未结 5 1066
自闭症患者
自闭症患者 2021-01-02 01:04

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;
         


        
相关标签:
5条回答
  • 2021-01-02 01:24

    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.

    0 讨论(0)
  • 2021-01-02 01:28
    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));
    
    0 讨论(0)
  • 2021-01-02 01:38

    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.#########"));
    
    0 讨论(0)
  • 2021-01-02 01:41
    Console.WriteLine(dummy.ToString("N5"));
    

    where 5 its number of decimal places

    0 讨论(0)
  • 2021-01-02 01:44
    string dum = string.Format("{0:f99}",dummy).TrimEnd('0');
    if (dum.EndsWith(",")) dum = dum.Remove(dum.Length - 1);
    
    0 讨论(0)
提交回复
热议问题