Lazy Diary @ Hatena Blog

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

Rounding strategy in Java/JavaScript/PowerShell

tl;dr

  • Java: Floor in type casting. Round half up for Math.round(). You can choose rouding strategy for BigDecimal.
  • JavaScript: Round half up for Math.round(). Round half away from zero for toFixed().
  • PowerShell (.NET CLR): Round half to even (bankers' rounding) in type casting, and [math]::Round(). You can choose rouding strategy in [math]::Round() with optional argument.

Java

java> double [] arr = {-3.5,-2.5,-1.5,-0.5,0.5,1.5,2.5,3.5};
java> for (int i=0; i<arr.length; i++) { System.out.println((int)arr[i]); }
-3
-2
-1
0
0
1
2
3
java> for (int i=0; i<arr.length; i++) { System.out.println(Math.round(arr[i])); }
-3
-2
-1
0
1
2
3
4
java> for (int i=0; i<arr.length; i++) { System.out.println(BigDecimal.valueOf(arr[i]).setScale(0,BigDecimal.ROUND_HALF_UP)); }
-4
-3
-2
-1
1
2
3
4
java> for (int i=0; i<arr.length; i++) { System.out.println(BigDecimal.valueOf(arr[i]).setScale(0,BigDecimal.ROUND_HALF_DOWN)); }
-3
-2
-1
0
0
1
2
3
java> for (int i=0; i<arr.length; i++) { System.out.println(BigDecimal.valueOf(arr[i]).setScale(0,BigDecimal.ROUND_HALF_EVEN)); }
-4
-2
-2
0
0
2
2
4

JavaScript

var arr = [-3.5,-2.5,-1.5,-0.5,0.5,1.5,2.5,3.5];
for (i in arr) { console.log(Math.round(arr[i])); }
-3
-2
-1
-0
1
2
3
4
undefined
for (i in arr) { console.log((arr[i]).toFixed()); }
-4
-3
-2
-1
1
2
3
4

PowerShell

see http://satob.hatenablog.com/entry/2017/06/01/234802 .