nilFi
nilFi

Reputation: 195

Java division returns incorrect result

 public static void main(String[] args) {
        final long a= 24 * 60 * 60 * 1000 * 1000;
        final long b= 24 * 60 * 60 * 1000;

        System.out.println(a/b);
 }

It should return 1000, but returns 5 why?

Upvotes: 2

Views: 279

Answers (5)

stack man
stack man

Reputation: 2413

You can use BigInteger or Long:

public static void main(String[] args) {
        final BigInteger a = new BigInteger("24");
        //multiply by creating big integers....
        final BigInteger b = new BigInteger("60")

        System.out.println(a.divide(b));
 }

Upvotes: 0

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62854

24 * 60 * 60 * 1000 is 86400000. If you multiply it by 1000, it will overflow the int type (because the maximum value that an int can hold is 2147483647 which is a lot less than 86400000000) and you will get 500654080 for a.

Then, when you divide the result by 86400000, you will get 5.

In order to fix this, you need to explicitly specify that the result from the multiplication will be long - this is because all the numeric operators in Java produce integers, unless explicitly instructed to produce some other numeric type.

Just appending a L on some of the operands will be sufficient:

final long a = 24 * 60 * 60 * 1000 * 1000L;

Upvotes: 7

SOP
SOP

Reputation: 801

Agree with above answers You can achieve what you want in below two ways:

public static void main(String[] args) {
        //way 1
        final long a =(long) 24 * 60 * 60 * 1000 * 1000;
        final long b = (long)24 * 60 * 60 * 1000;
        System.out.println(a / b);
        //way 2
        final long a1 = 24 * 60 * 60 * 1000 * 1000L;
        final long b1 = 24 * 60 * 60 * 1000L;
        System.out.println(a1 / b1);
    }

Upvotes: 1

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35547

24 * 60 * 60 * 1000 * 1000 this cause numeric overflow since it will consider as an int value. So you will get odd result. You should use long here.

You should use 24 * 60 * 60 * 1000 * 1000L (This is how you define long)

How to initialize long in Java?

Upvotes: 1

Masudul
Masudul

Reputation: 21961

Plain number in java considered as int. You need to append L to convert to long. Without L a =500654080, which is wrong.

 final long a= 24 * 60 * 60 * 1000 * 1000L;// Append L

Upvotes: 1

Related Questions