如何在c#中舍入浮点数

How to round float in c#

我想获取数字,其中.ToString()转换总长度<= 7。例如

 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

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

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

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

如果您要使用它的全部目的是将其显示为字符串(如更新中所述),则使用 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