该类Math
为您提供了用于向上和向下舍入的方法,它们分别是Math.Ceiling()
和Math.Floor()
。它们的工作方式类似Math.Round()
,但它们有一个特殊性,它们只接收一个值并将它们四舍五入到整个部分。
因此,您需要Math.Pow()
将该值乘以 10 到您需要四舍五入的 n 小单位,然后您需要除以相同的乘积值。
请务必注意,该Math.Pow()
方法的输入参数是double
,因此您需要将它们转换为double
.
例如:
当您要将值四舍五入为小数点后 3 位时(假设值类型为decimal
):
double decimalsNumber = 3;
decimal valueToRound = 1.1835675M;
// powerOfTen must be equal to 10^3 or 1000.
double powerOfTen = Math.Pow(10, decimalsNumber);
// rounded must be equal to Math.Ceiling(1.1835675 * 1000) / 1000
decimal rounded = Math.Ceiling(valueToRound * (decimal)powerOfTen) / (decimal)powerOfTen;
Result: rounded = 1.184
当您要将值向下舍入到小数点后 3 位时(假设值类型为decimal
):
double decimalsNumber = 3;
decimal valueToRound = 1.1835675M;
// powerOfTen must be equal to 10^3 or 1000.
double powerOfTen = Math.Pow(10, decimalsNumber);
// rounded must be equal to Math.Floor(1.1835675 * 1000) / 1000
decimal rounded = Math.Floor(valueToRound * (decimal)powerOfTen) / (decimal)powerOfTen;
Result: rounded = 1.183
To reference how to use them more specificaly and to get more information and about both methods you can see these pages from the oficial MSDN Microsoft site:
Math Class
Math.Pow Method (Double, Double)
Math.Floor Method (Decimal)
Math.Floor Method (Double)
Math.Ceiling Method (Decimal)
Math.Ceiling Method (Double)