1

I'm seeing differences between the built in round() function in Python and Java's java.lang.Math.round() function.

In Python we see..

Python 2.7.6 (default, Sep  9 2014, 15:04:36) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> round(0.0)
0.0
>>> round(0.5)
1.0
>>> round(-0.5)
-1.0

And in Java..

System.out.println("a: " + Math.round(0.0));
System.out.println("b: " + Math.round(0.5));
System.out.println("c: " + Math.round(-0.5));

a: 0
b: 1
c: 0

Looks like Java is always rounding up while Python rounds down for negative numbers.

What's the best way to get Python style rounding behavior in Java?

Sean Connolly
  • 5,692
  • 7
  • 37
  • 74
  • Related question but without a proposed solution: [Rounding negative numbers in Java](http://stackoverflow.com/questions/269721/rounding-negative-numbers-in-java) – Sean Connolly Jan 18 '15 at 13:24

4 Answers4

2

One possible way:

public static long symmetricRound( double d ) {
    return d < 0 ? - Math.round( -d ) : Math.round( d );
}

If the number is negative, round its positive value, then negate the result. If it's positive or zero, just use Math.round() as is.

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
1

You could maybe try:

float a = -0.5;
signum(a)*round(abs(a));
rbennett485
  • 1,907
  • 15
  • 24
  • It will be good if you add a few words explanation to your answer – user902383 Jan 18 '15 at 14:21
  • 1
    Not to be deliberately unhelpful, but I think it is reasonable to expect someone to work out why this works themselves. If you are unfamiliar with any of the the methods they are all in the documentation [here](http://docs.oracle.com/javase/8/docs/api/java/lang/Math.html) – rbennett485 Jan 18 '15 at 14:41
1

The round() function in Python and java works completely different.

In java, we use the normal mathematical calculation for rounding up the value

import java.lang.*;
public class HelloWorld{
        public static void main(String []args){
        System.out.println(Math.round(0.5));
        System.out.println(Math.round(1.5));
        System.out.println(Math.round(-0.5));
        System.out.println(Math.round(-1.5));
        System.out.println(Math.round(4.5));
        System.out.println(Math.round(3.5));
     }
}
$javac HelloWorld.java
$java -Xmx128M -Xms16M HelloWorld
1
2
0
-1
5
4

But in Python, for odd numbers the answer is rounded up to even numbers whereas when the number is even then no rounding up takes place.

>>> round(0.5)
0
>>> round(1.5)
2
>>> round(-0.5)
0
>>> round(-1.5)
-2
>>> round(4.5)
4
>>> round(3.5)
4
0

Just make your own round method:

public static double round(double n) {
    if (n < 0) {
        return -1 * Math.round(-1 * n);
    }

    if (n >= 0) {
        return Math.round(n);
    }
}
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70