如何仅显示带有两位非零小数的数字?
例如:
对于0.00045578,我想要0.00045;对于1.0000533535,我想要1.000053。
如何仅显示带有两位非零小数的数字?
例如:
对于0.00045578,我想要0.00045;对于1.0000533535,我想要1.000053。
我的解决方案是将数字转换为字符串。搜索“.”,然后计算零直到找到一个非零数字,然后取两个数字。
这不是一个优雅的解决方案,但我认为它会给你一致的结果。
这方面没有内置的格式。
您可以获取数字的小数部分,并计算有多少个零,直到获得两位数字,并从中组合出格式。例如:
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..
)。 - phipsgablerprivate 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;
}
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));