【问题标题】:How to round float in c#如何在c#中舍入浮点数
【发布时间】:2015-09-07 14:37:07
【问题描述】:

我要获取数字,.ToString() 转换总长度

 1. 1.23456789     - > 1.23457 
 2. 12345.789      - > 12345.8
 3. 123456789.1234 - > 1.235E8
 4. 0.00001234 - > 1.23E-8

我想使用非常快速的解决方案,因为使用大文件。

这段代码可以部分解决这个问题,但是不起作用

                    int power = (int)Math.Log10(f) + 1;
                    f = f / (float)Math.Pow(10, power);
                    f = (float)Math.Round(f, 5);
                    f = f * (float)Math.Pow(10, power);

例如 f = 7.174593E+10 四舍五入后变成0.71746(对我来说很好)

当我将它乘以10^11 时,它变成7.17459948E+10

但我期待7.71746E+10

UPD。 结果我想得到字符串,而不是数字。

【问题讨论】:

  • 听起来你需要更多地了解二进制浮点数的表示方式。举个简单的例子,0.1 不能完全表示为float。您可能应该考虑您希望基础值是什么以及您希望如何在文本中表示它以进行显示等。
  • String.format("{f:0.00000}",f) 有用吗? (可能需要为 0,00000,具体取决于区域设置)。
  • 为什么需要这样的数字格式?您只想以任何形式输出结果(String.Format 将成为您的朋友),还是需要结果以进行进一步计算?

标签: c# string optimization rounding


【解决方案1】:

如果您想四舍五入以便稍后在计算中使用它,请使用 Math.Round((decimal)myDouble, 3)。

如果您不打算在计算中使用它但需要显示它,请使用 double.ToString("F3")。

【讨论】:

    【解决方案2】:

    如果您只想将其显示为字符串(如更新中所述),请使用String.format()

    //one of these should output it correctly the other uses the wrong character as
    //decimal seperator (depends on globalization settings)
    String.format("{0:0,00000}",f);//comma for decimal
    String.format("{0:0.00000}",f);//point for decimal
    //how it works: first you say {0} meaning first variable after the text " "
    //then you specify the notation :0,00000 meaning 1 number before the seperator at least
    // and 5 numbers after.
    

    例子

    f = 0,123456789
    String.format("Text before the number {0:0.00000} Text after the number",f);
    //output:
    //Text before the number 0,12345 Text after the number
    
    //input: 123456789.1234
    textBox2.Text = string.Format("{0:0,0##E0}", f); 
    //output: 1.235E5
    

    【讨论】:

    • 这个转换 123456789.1234 -> 1.235E8 怎么样?
    • 用一点谷歌我发现了这个` textBox2.Text = string.Format("{0:E2}", f); ` 那样它将转到 1.23E008,我不知道为什么 0 在 8 之前,但我认为如果你在谷歌上搜索 string.format 你可以找到正确的格式代码。
    • @virty 以为我也会寻找它,发现它很快就将它添加到 awnser 中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    • 2016-12-28
    • 2012-09-11
    相关资源
    最近更新 更多