Sean Connolly
Sean Connolly

Reputation: 5801

Python style round() in Java

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?

Upvotes: 1

Views: 1526

Answers (4)

rutuja_mhankale
rutuja_mhankale

Reputation: 19

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

Upvotes: 1

Malik Brahimi
Malik Brahimi

Reputation: 16721

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);
    }
}

Upvotes: 0

RealSkeptic
RealSkeptic

Reputation: 34638

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.

Upvotes: 2

rbennett485
rbennett485

Reputation: 2163

You could maybe try:

float a = -0.5;
signum(a)*round(abs(a));

Upvotes: 1

Related Questions