Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何仅显示不等于0的前2位小数_C# - Fatal编程技术网

C# 如何仅显示不等于0的前2位小数

C# 如何仅显示不等于0的前2位小数,c#,C#,如何仅显示2个not=零小数的数字 例如: 对于0.00045578,我想要0.00045,对于1.000053335,我想要1.000053,我的解决方案是将数字转换为字符串。搜索“.”,然后数零,直到找到一个非零数字,然后取两个数字 这不是一个优雅的解决方案,但我认为它将为您提供一致的结果。没有内置的格式 你可以得到这个数字的分数部分,然后数一数有多少个零,直到你得到两位数,然后把它的格式组合起来。例如: double number = 1.0000533535; double i = M

如何仅显示2个not=零小数的数字

例如:


对于0.00045578,我想要0.00045,对于1.000053335,我想要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);

注意:给定的代码仅在数字的小数部分有效,而不适用于负数。如果需要支持这些情况,则需要添加检查。

尝试此功能,使用解析查找小数位数,而不是查找零(它也适用于负数):


您可以使用以下技巧:

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));

由于四舍五入,第一个应该是0.00046吗?那么如果你得到45.2500001342,你希望它是45.25正确吗?@DavidYaw:不需要四舍五入@craig1231:yes@Jorge:变量是一个double我要写一些等价的东西,只是没有循环:
-ceil(log(x%1,10))
直接提供第一个非零数字的索引(例如
log(0.0002)==-3.69..
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;
}
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));