Powershell: convert a fraction to an integer - surprising rounding behavior

前端 未结 2 1670
野趣味
野趣味 2020-12-10 18:45

I have a interesting question on ints with decimals.

Assuming I do the following:

[int] $a = 5/2
$a

I\'ve tried it 10 times to be

2条回答
  •  温柔的废话
    2020-12-10 19:14

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

    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.

提交回复
热议问题