如何在 C# 中舍入到最接近的整数
本文关键字:最接近 整数 舍入 | 更新日期: 2023-09-27 18:20:14
如何将值舍入到最接近的整数?
例如:
1.1 => 1
1.5 => 2
1.9 => 2
"Math.Ceiling(("对我没有帮助。有什么想法吗?
有关详细信息,请参阅官方文档。例如:
基本上,您给Math.Round
方法三个参数。
- 要舍入的值。
- 要在值后保留的小数位数。
- 可以调用以使用 AwayFromZero 舍入的可选参数。(除非四舍五入不明确,否则忽略,例如 1.5(
示例代码:
var roundedA = Math.Round(1.1, 0); // Output: 1
var roundedB = Math.Round(1.5, 0, MidpointRounding.AwayFromZero); // Output: 2
var roundedC = Math.Round(1.9, 0); // Output: 2
var roundedD = Math.Round(2.5, 0); // Output: 2
var roundedE = Math.Round(2.5, 0, MidpointRounding.AwayFromZero); // Output: 3
var roundedF = Math.Round(3.49, 0, MidpointRounding.AwayFromZero); // Output: 3
现场演示
如果要向上舍入 .5 值,则需要MidpointRounding.AwayFromZero
。不幸的是,这不是Math.Round()
的默认行为。如果使用MidpointRounding.ToEven
(默认值(,则值将舍入到最接近的偶数(1.5
四舍五入为2
,但2.5
也舍入为2
(。
Math.Ceiling
总是向上舍入(朝向天花板(
Math.Floor
始终向下舍入(朝向地板(
你所追求的只是
Math.Round
根据这篇文章进行哪些轮次
你需要Math.Round
,而不是Math.Ceiling
。 Ceiling
总是向上"舍入",而Round
根据小数点后的值向上或向下舍入。
这个手册,也有点可爱的方式:
double d1 = 1.1;
double d2 = 1.5;
double d3 = 1.9;
int i1 = (int)(d1 + 0.5);
int i2 = (int)(d2 + 0.5);
int i3 = (int)(d3 + 0.5);
只需将 0.5 添加到任何数字,然后将其转换为 int(或下沉(,它将在数学上正确四舍五入:D
你可以按照其他人的建议(推荐(使用 Math.Round,或者你可以添加 0.5 并转换为 int(这将删除小数部分(。
double value = 1.1;
int roundedValue = (int)(value + 0.5); // equals 1
double value2 = 1.5;
int roundedValue2 = (int)(value2 + 0.5); // equals 2
只是一个提醒。当心双倍。
Math.Round(0.3 / 0.2 ) result in 1, because in double 0.3 / 0.2 = 1.49999999
Math.Round( 1.5 ) = 2
你有 Math.Round 函数,它完全可以做你想要的。
Math.Round(1.1) results with 1
Math.Round(1.8) will result with 2.... and so one.
四舍五入到最接近的 5,或者如果它已经被 5 整除,则不会改变
public static double R(double x)
{
// markup to nearest 5
return (((int)(x / 5)) * 5) + ((x % 5) > 0 ? 5 : 0);
}
我正在寻找这个,但我的例子是取一个数字,例如 4.2769 并将其放在一个跨度中,仅为 4.3。 不完全相同,但如果这有帮助:
Model.Statistics.AverageReview <= it's just a double from the model
然后:
@Model.Statistics.AverageReview.ToString("n1") <=gives me 4.3
@Model.Statistics.AverageReview.ToString("n2") <=gives me 4.28
等。。。
使用Math.Round(number)
舍入到最接近的整数。
使用 Math.Round
:
double roundedValue = Math.Round(value, 0)
var roundedVal = Math.Round(2.5, 0);
它将给出结果:
var roundedVal = 3
如果您使用的是整数而不是浮点数,那么这就是方法。
#define ROUNDED_FRACTION(numr,denr) ((numr/denr)+(((numr%denr)<(denr/2))?0:1))
这里的">numr"和"denr">都是无符号整数。
编写自己的 round 方法。像这样,
function round(x)
rx = Math.ceil(x)
if (rx - x <= .000001)
return int(rx)
else
return int(x)
end
我真正想要的
float myRound(float numberIn, int numDig)
{
// float numberIn: number to round
// int numDig: number of digits after the point
// myRound(123.456,2) => 123.45
// myRound(123.456,1) => 123.4
// myRound(123.456,-1) => 120
float tenPow = Mathf.Pow(10, numDig);
return ((int)tenPow*numberIn)/tenPow;
}
decimal RoundTotal = Total - (int)Total;
if ((double)RoundTotal <= .50)
Total = (int)Total;
else
Total = (int)Total + 1;
lblTotal.Text = Total.ToString();