如何将数字向上舍入为2位小数

use*_*496 -1 c# numbers rounding

我正在尝试使用C#对数字进行舍入,以便它总是向下一个数字舍入.例如:

0.409 -> 0.41
0.401 -> 0.41
0.414 -> 0.42
0.499 -> 0.50
0.433 -> 0.44
Run Code Online (Sandbox Code Playgroud)

有没有办法使用.NET内置函数执行此操作?

小智 5

Math.Ceiling 可以使用.

Math.Ceiling 虽然舍入到最接近的整数,所以我建议你做一些除法/乘法:

var notRounded = 0.409;
var rounded = Math.Ceiling(notRounded * 100) / 100;
Run Code Online (Sandbox Code Playgroud)

说明:notRounded*100给你40.9.Math.Ceiling将返回41,因此将其再次划分为"将其恢复"为原始的十进制形式:0.41.