Search code examples
powershellcastingintegerroundingbankers-rounding

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


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 sure, and powershell always returns 2

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?

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


Solution

  • [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.