C# 有小数点金额,如果有,请将小数点后的位数减至2位
有小数位数,如果存在,想将小数位数减少到2位您是否尝试过使用C# 有小数点金额,如果有,请将小数点后的位数减至2位,c#,math,decimal,C#,Math,Decimal,有小数位数,如果存在,想将小数位数减少到2位您是否尝试过使用value=decimal.Round(value,2) 例如: using System; class Test { static void Main() { decimal d = 1234.5678m; Console.WriteLine("Before: {0}", d); // Prints 1234.5678 d = decimal.Round(d,
value=decimal.Round(value,2)
例如:
using System;
class Test
{
static void Main()
{
decimal d = 1234.5678m;
Console.WriteLine("Before: {0}", d); // Prints 1234.5678
d = decimal.Round(d, 2);
Console.WriteLine("After: {0}", d); // Prints 1234.57
}
}
请注意,这是四舍五入,而不仅仅是修剪(所以这里是四舍五入)。。。你到底需要什么?Decimal
struct很可能支持您需要执行的任何操作。咨询更多选项
decimal.Truncate(myDecimal * 100) / 100
这将删除前两位小数点后的所有内容。有关舍入的信息,请参见Jon的答案。这应该有效(编辑:修复以删除舍入):
如果只是出于显示目的,您可以使用:
Console.Out.WriteLine("Number is: {0:F2}", myDecimalNumber);
我用这个:
数学四舍五入(MyDecimalValue,2) 你是想“去掉多余的小数”还是想像乔恩说的那样取整?截断还是取整?要截断,请参见:在C#
^
中,isxor
。此外,如果有人使用decimal
很可能是故意选择的,他们可能不想要其他类型(除此之外,您的示例在任何情况下都是不正确的)。对,抱歉应该是math.exp()。否则怎么办?Int
不是C#中的一种类型,然后你要做整数除法,反正不留小数点。Math.Round可以做银行家的四舍五入。
Console.Out.WriteLine("Number is: {0:F2}", myDecimalNumber);