4

When I am trying to round the values the results are different. Please observe the below Output. It rounds up for Odd numbers only. What's wrong I am doing.

PS C:\> [math]::Round(1.5)
2

PS C:\> [math]::Round(2.5)
2

PS C:\> [math]::Round(3.5)
4

PS C:\> [math]::Round(4.5)
4

PS C:\> [math]::Round(5.5)
6

PS C:\> [math]::Round(6.5)
6
Roger Lipscombe
  • 89,048
  • 55
  • 235
  • 380
Jeetcu
  • 43
  • 3
  • 10
  • 1
    Possible duplicate of [PowerShell \[Math\]::Round sometimes not rounding?](https://stackoverflow.com/questions/46286675/powershell-mathround-sometimes-not-rounding) –  Jul 09 '18 at 11:34
  • 2
    @LotPings - It looks more like math is using bankers rounding – Lieven Keersmaekers Jul 09 '18 at 11:43
  • See [this](https://stackoverflow.com/questions/48864295/powershell-int-variable-with-decimal-number/48864546#48864546) explanation for more clarity! – Vivek Kumar Singh Jul 09 '18 at 12:20
  • 1
    Alternatively you can use the string format `N0` as in `"{0,N0}" -f 2.5` or `(2.5).ToString('N0')` –  Jul 09 '18 at 12:24

1 Answers1

6

[math] uses bankers rounding

From the comment section in Rounding numbers

...which means numbers are rounded to the nearest even number. This doesn’t follow the rules I learned with math rounding where something ending in 5 is always rounded up to the next higher level number. To get the Round function to behave the way most of us learned math rules, you use the additional AwayFromZero switch (Dan Sheehan).

If you always want to round up, you can use AwayFromZero

[math]::Round(2.5, 0, [System.MidpointRounding]::AwayFromZero)
Lieven Keersmaekers
  • 57,207
  • 13
  • 112
  • 146
  • I was about to posting the same link, might be easier/shorter to add `.001` –  Jul 09 '18 at 11:57
  • Shorter indeed but impov the intent is more explicit using AwayFromZero and it at least gives you something to search on ;) *(it was new to me)* – Lieven Keersmaekers Jul 09 '18 at 12:11