C# 格式正好是小数点后的两位到小数点后 n 位

本文关键字:小数点 两位 格式 正好是 | 更新日期: 2023-09-27 18:32:19

我想在 komma 之后不断显示精确的 n 位小数。

所以(for = 2)如果我有 13.4589,它应该显示 13.49;如果是 1512.0000,它应该显示 1512.00 而不仅仅是 1512

我试过这个:

double value; //does contain the value to dislplay
int numberOfDecimals; //does contain the number of decimals I want to have permanently displayed
///first try
int temp = Convert.ToInt32(Math.Pow(10, numberOfDecimals));
string result1 = ((Math.Truncate(value * temp) / temp).ToString();
///second try
string temp = "0.";
for(int i = 0; i<numberOfDecimals;i++)
{
temp = temp + "#";
}
string result2 = value.ToString(temp);

两者都不会导致想要的输出(每当出现带有".000"的内容时,不会显示 komma 后面的零).. 我必须更改什么?

C# 格式正好是小数点后的两位到小数点后 n 位

您可以使用

F格式说明符:

string result1 = ((Math.Truncate(value * temp) / temp).ToString("F2");