如何仅显示前两位小数不为零

6

如何仅显示带有两位非零小数的数字?

例如:

对于0.00045578,我想要0.00045;对于1.0000533535,我想要1.000053。


第一个数字应该是0.00046吗,因为四舍五入的原因? - David Yaw
所以如果你得到了45.2500001342,你想要它变成45.25对吗? - craig1231
@ DavidYaw:不需要四舍五入 @ craig1231:是的 @ Jorge:变量是一个双精度浮点数 - Alexis Cimpu
4个回答

3

我的解决方案是将数字转换为字符串。搜索“.”,然后计算零直到找到一个非零数字,然后取两个数字。

这不是一个优雅的解决方案,但我认为它会给你一致的结果。


3

这方面没有内置的格式。

您可以获取数字的小数部分,并计算有多少个零,直到获得两位数字,并从中组合出格式。例如:

double number = 1.0000533535;

double i = Math.Floor(number);
double f = number % 1.0;

int cnt = -2;
while (f < 10) {
  f *= 10;
  cnt++;
}

Console.WriteLine("{0}.{1}{2:00}", i, new String('0', cnt), f);

输出:

1.000053

注意:仅当数字实际存在小数部分时,给定的代码才有效,对于负数则无效。 如果您需要支持这些情况,则需要添加检查。

我本来想写一个等价的东西,只是没有循环:-ceil(log(x % 1, 10)) 直接给出了第一个非零数字的索引(例如 log(0.0002) == -3.69..)。 - phipsgabler

1
尝试使用解析函数来查找小数位数的数量,而不是寻找零(它也适用于负数):
private static string GetTwoFractionalDigitString(double input)
{
    // Parse exponential-notation string to find exponent (e.g. 1.2E-004)
    double absValue = Math.Abs(input);
    double fraction = (absValue - Math.Floor(absValue));
    string s1 = fraction.ToString("E1");
    // parse exponent peice (starting at 6th character)
    int exponent = int.Parse(s1.Substring(5)) + 1;

    string s = input.ToString("F" + exponent.ToString());

    return s;
}

0
你可以使用这个技巧:
int d, whole;
double number = 0.00045578;
string format;
whole = (int)number;
d = 1;
format = "0.0";
while (Math.Floor(number * Math.Pow(10, d)) / Math.Pow(10, d) == whole)
{
    d++;
    format += "0";
}
format += "0";
Console.WriteLine(number.ToString(format));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接