在 C# 中四舍五入到小数点后两位 [英] Rounding up to 2 decimal places in C#
问题描述
我有一个十进制数,可能如下所示:
I have a decimal number which can be like the following:
189.182
我想把这个向上四舍五入到小数点后两位,所以输出如下:
I want to round this up to 2 decimal places, so the output would be the following:
189.19
在 Math 类中是否有内置的功能或其他功能?我知道天花板函数存在,但这似乎不是我想要的 - 它会四舍五入到最近的整数,所以在这种情况下只是189".
Is there built in functionality for this in the Math class, or something else? I know the ceiling function exists but this doesn't seem to do what I want - it'll round to the nearest int, so just '189' in this case.
推荐答案
乘以 100,调用天花板,除以 100 做我认为你要求的事情
Multiply by 100, call ceiling, divide by 100 does what I think you are asking for
public static double RoundUp(double input, int places)
{
double multiplier = Math.Pow(10, Convert.ToDouble(places));
return Math.Ceiling(input * multiplier) / multiplier;
}
用法如下:
RoundUp(189.182, 2);
这是通过将小数点向右移动 2 位(因此它位于最后 8 位的右侧)然后执行上限运算,然后将小数点移回其原始位置来实现的.
This works by shifting the decimal point right 2 places (so it is to the right of the last 8) then performing the ceiling operation, then shifting the decimal point back to its original position.
这篇关于在 C# 中四舍五入到小数点后两位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!