double在C#中显示2个非零小数?

时间:2016-09-27 03:28:10

标签: c#

我希望以字符串格式显示双变量的最大2位小数。如何编写一个函数来显示非零小数?

示例:

double intVar = 1;
double oneDice = 1.1;
double twoDice = 1.11;
double threeDice = 1.111;

Console.writeLine(yourFunction(intVar)); //output  1
Console.writeLine(yourFunction(oneDice)); //output  1.1
Console.writeLine(yourFunction(twoDice)); //output  1.11
Console.writeLine(yourFunction(threeDice)); //output  1.11

1 个答案:

答案 0 :(得分:0)

从我的评论中的链接https://stackoverflow.com/a/2453982/6741868和其他一些代码:

public string yourFunction(double val)
{
    double x = val;

    if (BitConverter.GetBytes(decimal.GetBits((decimal)val)[3])[2] > 2)   //check if there are more than 2 decimal places
    {
        x = Math.Truncate(val * 100) / 100;           
        string s = string.Format("{0:N2}", x);
        return s;
    }
    return x.ToString();
}

如果小数位数超过2个,则会截断其余小数位( NOT 舍入)并转换为显示2个小数位的字符串。

否则它只返回原始值,转换为字符串。

可以根据您的进一步需要随意修改功能,或者如果您想稍微调整输出字符串。

修改

经过个人测试的价值观:

1,1.1,1.11,1.111,1.138234732

结果:

1,1.1,1.11,1.11,1.13