Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

PowerShell does banker's rounding in type casting to int

Problem:

PowerShell rounds 0.5 to 0 (banker’s rounding) in type casting to int.

PS > @(-3.5,-2.5,-1.5,-0.5,0.5,1.5,2.5,3.5) | ForEach-Object { "{0} -> {1}" -F $_, [int]$_ }
-3.5 -> -4
-2.5 -> -2
-1.5 -> -2
-0.5 -> 0
0.5 -> 0
1.5 -> 2
2.5 -> 2
3.5 -> 4

Hey, Scripting Guy! Blog says use [math]::Round() to round numbers, but [math]::Round() does also banker’s rounding in default.

PS > @(-3.5,-2.5,-1.5,-0.5,0.5,1.5,2.5,3.5) | ForEach-Object { "{0} -> {1}" -F $_, [math]::Round($_) }       -3.5 -> -4                                                                                                              
-2.5 -> -2
-1.5 -> -2
-0.5 -> 0
0.5 -> 0
1.5 -> 2
2.5 -> 2
3.5 -> 4

Solution:

Use [math]::Round() with option "AwayFromZero" when you want to round 0.5 to 1.

PS > @(-3.5,-2.5,-1.5,-0.5,0.5,1.5,2.5,3.5) | ForEach-Object { "{0} -> {1}" -F $_, [math]::Round($_,0,"AwayFromZero") }
-3.5 -> -4
-2.5 -> -3
-1.5 -> -2
-0.5 -> -1
0.5 -> 1
1.5 -> 2
2.5 -> 3
3.5 -> 4