C#中的指数

时间:2018-04-18 16:26:06

标签: c# floating-point floating-accuracy

int trail = 14;
double mean = 14.00000587000000;
double sd = 4.47307944700000;

double zscore = double.MinValue;

zscore = (trail - mean) / sd; //zscore at this point is exponent value -1.3122950464645662E-06

zscore = Math.Round(zscore, 14); //-1.31229505E-06

Math.Round()也保留指数值。是否应使用zscore.ToString("F14")代替Math.Round()函数将其转换为非指数值?请解释一下。

1 个答案:

答案 0 :(得分:7)

这些是完全独立的问题。

Math.Round实际上会返回一个新值,四舍五入到指定的小数(至少是ar,就像浮点数一样)。

您可以在任何地方重复使用此结果值,并在需要时以16位小数精度显示它,但不应与原始相同。

它以指数表示法显示的事实与Round无关。

在数字上使用ToString("F14")时,这只是一个显示规范,不会以任何方式修改基础值。基础值可能是一个否则将会显示为指数表示法的数字,并且可能或可能实际上有14位有效数字。

它只是强制数字显示为完整小数,不带指数表示法,并指定位数。所以它似乎是你真正想要的。

示例:

(可在线执行:http://rextester.com/PZXDES55622

double num = 0.00000123456789;

Console.WriteLine("original :");
Console.WriteLine(num.ToString());
Console.WriteLine(num.ToString("F6"));
Console.WriteLine(num.ToString("F10"));
Console.WriteLine(num.ToString("F14"));

Console.WriteLine("rounded to 6");
double rounded6 = Math.Round(num, 6);
Console.WriteLine(rounded6.ToString());
Console.WriteLine(rounded6.ToString("F6"));
Console.WriteLine(rounded6.ToString("F10"));
Console.WriteLine(rounded6.ToString("F14"));

Console.WriteLine("rounded to 10");
double rounded10 = Math.Round(num, 10);
Console.WriteLine(rounded10.ToString());
Console.WriteLine(rounded10.ToString("F6"));
Console.WriteLine(rounded10.ToString("F10"));
Console.WriteLine(rounded10.ToString("F14"));

将输出:

original :
1,23456789E-06
0,000001
0,0000012346
0,00000123456789
rounded to 6
1E-06
0,000001
0,0000010000
0,00000100000000
rounded to 10
1,2346E-06
0,000001
0,0000012346
0,00000123460000
相关问题