Powershell:将小数转换为整数-令人惊讶的舍入行为 [英] Powershell: convert a fraction to an integer - surprising rounding behavior

查看:1067
本文介绍了Powershell:将小数转换为整数-令人惊讶的舍入行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对带小数的整数有一个有趣的问题.

I have a interesting question on ints with decimals.

假设我执行以下操作:

[int] $a = 5/2
$a

我已经尝试了十次,以确保powershell始终返回2

I've tried it 10 times to be sure, and powershell always returns 2

在这种情况下是否有办法强制Powershell向上或向下取整?默认情况下是否已将其设置为向下取整?

Is there a way to force Powershell to round up or down in such circumstances and by default has it been set to round down?

我假设取决于机器和Powershell环境,在某些情况下我可能会得到3,在其他情况下我可能会得到2.

I'm assuming depending on the machine and Powershell environment, I may get 3 at some points and 2 at others.

推荐答案

[Math]::Floor($a) --> 2
[Math]::Ceiling($a)--> 3
[Math]::Round($a) --> 2

Floor将给您前面的整数,而Ceiling将给您后面的整数. 但是,如果要使用Round函数将其四舍五入,它将遵循中点舍入(中点处的舍入历来远离零),如下所示-

Floor will give you the preceding whole number and Ceiling will be providing the succeeding whole number. But if you want to round it up, using the Round function, it will follow midpoint rounding (Rounding at midpoint is historically away from zero), as demonstrated below -

[Math]::Round(2.50) --> 2
[Math]::Round(2.51) --> 3
[Math]::Round(2.49) --> 2
[math]::Round(2.50,[System.MidpointRounding]::AwayFromZero) --> 3
[math]::Round(2.49,[System.MidpointRounding]::AwayFromZero) --> 2
[math]::Round(2.51,[System.MidpointRounding]::AwayFromZero) --> 3

您可以根据需要使用这两种功能.

You can use either functions depending upon your requirement.

这篇关于Powershell:将小数转换为整数-令人惊讶的舍入行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆