Ale*_* LE 446

这有效:

inputValue = Math.Round(inputValue, 2);
Run Code Online (Sandbox Code Playgroud)

  • 如果值为 48.0000。它不会导致 48.00。双输入值 = 48.00; inputValue = Math.Round(inputValue, 2); 只会产生 48。任何战争? (3认同)

nan*_*din 99

Math.Round(inputValue, 2, MidpointRounding.AwayFromZero)
Run Code Online (Sandbox Code Playgroud)

  • 建议银行使用双打是可怕的家伙,不要使用货币的近似值. (38认同)
  • @raggi我害怕一些(银行)做...这可以解释很多东西 (6认同)
  • 这实际上应该是应该使用的.银行等大多数业务都是使用这种方法完成的(MidpointRounding.AwayFromZero). (4认同)
  • 是的,我相信这就是电影"办公室空间"之后制作的 - 四舍五入没有人会注意到的分数.关于什么时候任意使用舍入要小心的好点. (4认同)
  • 并且作为很久以前原始超人电影之一的情节的一部分。 (3认同)
  • @JamesWestgate“他们在《超人 3》中做到了” (2认同)

Gag*_*age 25

你应该用

inputvalue=Math.Round(inputValue, 2, MidpointRounding.AwayFromZero)
Run Code Online (Sandbox Code Playgroud)

Math.Round

Math.Round将双精度浮点值舍入到指定的小数位数.

MidpointRounding

指定数学舍入方法应如何处理两个数字中间的数字.

基本上,上面的函数将获取您的inputvalue并将其四舍五入为2(或您指定的任何数字)小数位.随着MidpointRounding.AwayFromZero当一个数字是中间两个人之间,实际上是朝着四舍五入是远离零最接近的数字.您还可以使用另一个选项,向最近的偶数舍入.


小智 21

另一种简单的方法是使用带参数的ToString.例:

float d = 54.9700F;    
string s = d.ToString("N2");
Console.WriteLine(s);
Run Code Online (Sandbox Code Playgroud)

结果:

54.97
Run Code Online (Sandbox Code Playgroud)


rec*_*ive 18

使用Math.Round

value = Math.Round(48.485, 2);
Run Code Online (Sandbox Code Playgroud)


rez*_*e08 8

你可以从下面尝试一下.这有很多方法.

1. 
 value=Math.Round(123.4567, 2, MidpointRounding.AwayFromZero) //"123.46"
2.
 inputvalue=Math.Round(123.4567, 2)  //"123.46"
3. 
 String.Format("{0:0.00}", 123.4567);      // "123.46"
4. 
string.Format("{0:F2}", 123.456789);     //123.46
string.Format("{0:F3}", 123.456789);     //123.457
string.Format("{0:F4}", 123.456789);     //123.4568
Run Code Online (Sandbox Code Playgroud)


not*_*yle 6

使用插值字符串,这会生成一个四舍五入的字符串:

var strlen = 6;
$"{48.485:F2}"
Run Code Online (Sandbox Code Playgroud)

输出

"48.49"
Run Code Online (Sandbox Code Playgroud)