将浮点数格式化为两位小数

285

我目前正在为客户的网站构建销售模块。到目前为止,我已经完美地计算了销售价格,但是我卡在了将输出格式化为2个小数位。

我当前将此调用保存在变量中,以便可以将结果数据绑定到列表视图。

Sale = float.Parse(((x.Sale_Price - (x.Sale_Price * (x.Discount_Price / 100))).ToString())),

有人可以向我展示如何将输出格式化为2位小数吗?非常感谢!


1
请检查一下,我不确定但可能会起作用 ToString ("#.##"); - Syeda
9个回答

572

你可以将格式传递给ToString方法,例如:

myFloatVariable.ToString("0.00"); //2dp Number

myFloatVariable.ToString("n2"); // 2dp Number

myFloatVariable.ToString("c2"); // 2dp currency

标准数字格式字符串


61
"N2"和"C2"会在数字中添加千位分隔符,而"0.00"不会。 - Marc K
12
以防你不确定(我曾经也不确定),这些浮点数格式化的方法都会提供四舍五入。 - RenniePet
“00.00”是什么意思?为什么有些人会有多个0呢? - Marcos Pereira
1
@MarcosPereira 它将用零填充字符串。因此,1.1会变成字符串“01.10”,而22.2会变成“22.20”。这可能对排序或类似的操作很有用。 - Brynn McCullagh
“0.00”格式运行良好,但我在官方文档(上面链接的)中找不到任何有关它的内容,还是我眼瞎了? - R1PFake
1
@R1PFake - 在我提供的URL链接中有一些额外信息,可以通过访问链接页面进行查看。您可以在这里阅读更多:https://learn.microsoft.com/en-us/dotnet/api/system.int32.tostring?view=net-6.0#System_Int32_ToString_System_String_ 或者在这里:https://learn.microsoft.com/en-us/dotnet/api/system.double.tostring?view=net-6.0。请查找自定义格式。 - WraithNath

58

这是用于您想要使用插值字符串的情况。实际上我发布这篇文章是因为我已经厌倦了不断尝试和浏览大量文档来格式化标量。

$"{1234.5678:0.00}"        "1234.57"        2 decimal places, notice that value is rounded
$"{1234.5678,10:0.00}"     "   1234.57"     right-aligned
$"{1234.5678,-10:0.00}"    "1234.57   "     left-aligned
$"{1234.5678:0.#####}"     "1234.5678"      5 optional digits after the decimal point
$"{1234.5678:0.00000}"     "1234.56780"     5 forced digits AFTER the decimal point, notice the trailing zero
$"{1234.5678:00000.00}"    "01234.57"       5 forced digits BEFORE the decimal point, notice the leading zero
$"{1234.5612:0}"           "1235"           as integer, notice that value is rounded
$"{1234.5678:F2}"          "1234.57"        standard fixed-point
$"{1234.5678:F5}"          "1234.56780"     5 digits after the decimal point, notice the trailing zero
$"{1234.5678:g2}"          "1.2e+03"        standard general with 2 meaningful digits, notice "e"
$"{1234.5678:G2}"          "1.2E+03"        standard general with 2 meaningful digits, notice "E"
$"{1234.5678:G3}"          "1.23E+03"       standard general with 3 meaningful digits
$"{1234.5678:G5}"          "1234.6"         standard general with 5 meaningful digits
$"{1234.5678:e2}"          "1.23e+003"      standard exponential with 2 digits after the decimal point, notice "e"
$"{1234.5678:E3}"          "1.235E+003"     standard exponential with 3 digits after the decimal point, notice "E"
$"{1234.5678:N2}"          "1,234.57"       standard numeric, notice the comma
$"{1234.5678:C2}"          "$1,234.57"      standard currency, notice the dollar sign
$"{1234.5678:P2}"          "123,456.78 %"   standard percent, notice that value is multiplied by 100
$"{1234.5678:2}"           "2"              :)

性能警告

插值字符串的速度较慢。根据我的经验,这是速度从快到慢的顺序:

  1. value.ToString(format)+" blah blah"
  2. string.Format("{0:format} blah blah", value)
  3. $"{value:format} blah blah"

55

你需要做的第一件事是使用 decimal 类型来代替价格中的 float 类型。因为 float 不能准确地表示大多数十进制小数,所以绝对不能使用它。

完成这一步后,可以使用 Decimal.Round() 方法来将数字四舍五入到两位小数。


7
在这里将float称为“绝对不可接受”有些夸张,但使用Decimal类的想法确实是好的。 - user74696c
好观点。如果只有 OP 请求关于变量类型的建议。 - Cool guy
这可能是完全不可接受的,但我的手在这里被束缚了。我真的无法改变这种方法。它接受浮点数,而且没有方法重载。 - I try so hard but I cry harder

37

String.Format("{0:#,###.##}", value)

这个功能会以千位分隔符的形式显示value的值,精确到小数点后两位。

更复杂的例子可以在C#字符串格式化中找到:

String.Format("{0:$#,##0.00;($#,##0.00);Zero}", value);

如果传入的参数是1243.50,则会输出“$1,240.00”。如果参数是负数,则输出相同的格式但用括号括起来。如果数字为0,则输出字符串“Zero”。


35

7
如前所述,您需要使用格式化结果;这可以通过Write()WriteLine()Format()ToString()方法完成。
但是,还没有提到的是固定点格式,它允许指定小数点后的位数。它使用一个'F',后面跟着输出的小数位数,如示例所示。
Console.WriteLine("{0:F2}", 12);    // 12.00 - two decimal places
Console.WriteLine("{0:F0}", 12.3);  // 12 - ommiting fractions

5

我喜欢使用

$"{value:0.##}

如果有值,它可以选择性地显示小数。

例子:

$"{50.255:0.##} //50,25
$"{50.2:0.##}   //50,2
$"{50.00:0.##}  //50

5
string outString= number.ToString("####0.00");

3
在自定义格式中,"0"和"#"是不同的。 "0":如果存在相应数字,则用该数字替换零;否则,在结果字符串中出现零。 "#":如果存在相应数字,则用该数字替换"#"符号;否则,在结果字符串中不显示任何数字。参考链接 - 劉鎮瑲

0
    private float LimitDecimalPlace(double number,int limitPlace)
    {
        float result = 0;
        string sNumber = number.ToString();
        int decimalIndex = sNumber.IndexOf(".");
        if (decimalIndex != -1)
        {
            sNumber = sNumber.Remove(decimalIndex + limitPlace + 1);
        }
       
        result = float.Parse(sNumber);
        return result;
    }

1
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

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