C# 如何在c中圆化浮点#

C# 如何在c中圆化浮点#,c#,string,optimization,rounding,C#,String,Optimization,Rounding,我想得到一个数字,它是.ToString()转换的总长度如果你想取整以便在以后的计算中使用它,请使用Math.round((十进制)myDouble,3) 如果您不打算在计算中使用它,但需要显示它,请使用double.ToString(“F3”)。如果您要使用它的全部目的是将其显示为字符串(如更新中所述),请使用string.format() 范例 f = 0,123456789 String.format("Text before the number {0:0.00000} Text aft

我想得到一个数字,它是.ToString()转换的总长度如果你想取整以便在以后的计算中使用它,请使用Math.round((十进制)myDouble,3)


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

如果您要使用它的全部目的是将其显示为字符串(如更新中所述),请使用
string.format()

范例

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

在我看来,你需要更多地了解二进制浮点数是如何表示的。举一个简单的例子,0.1不能精确地表示为
浮点
。你可能应该考虑一下你想要的潜在价值是什么,你想在文本中显示它,等等。代码< > Strord.Frand(“{F:0 00000 }”,F)< /代码>是有用的吗?(可能是000000,具体取决于区域设置)。为什么数字需要这种格式?你只想以任何形式输出结果(而不是字符串。格式将是你的朋友),还是需要进一步计算的结果?这个转换怎么样123456789.1234->1.235E8?我用谷歌搜索了一下,找到了这个`textBox2.Text=String.Format({0:E2}),f)`那样的话,它会变成1.23E008,我不知道为什么0在8之前,但我认为如果你在谷歌上搜索
string.format
,你可以找到正确的格式代码。@virty认为我也会查找它,并很快找到它,我会将它添加到awnser中
                    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);
//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