Justinas
Justinas

Reputation: 57

Big long numerics dividing with round

I have problem with java then i want to divade big long type numerics for example if i divide 165600139 / 86400000 = 1.9, but my method return 1 without rounding :/

public static long calcDaysBefore(Date date) {
    int MILISECONDS_IN_DAY = 24 * 60 * 60 * 1000;
    long days = 0;
    if (date != null) {
        long current = getCurrentDate().getTime() - date.getTime();
        days = current / MILISECONDS_IN_DAY;
    }
    return days;
}

Upvotes: 0

Views: 95

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136022

actually the result is rounded, there are several rounding modes, see http://docs.oracle.com/javase/1.5.0/docs/api/java/math/RoundingMode.html, in your case you are getting the number of full days. For rounding to the closest long we can use

long days = Math.round(current / 8640000.0);

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533530

It is rounding down and is similar to doing

days = Math.floor((double) current / MILISECONDS_IN_DAY);

If you want to round half up you can write

days = (current + MILISECONDS_IN_DAY/2) / MILISECONDS_IN_DAY;

Using floating point you could use the following which is much slower.

days = Math.round((double) current / MILISECONDS_IN_DAY);

if you want to round up you can do

days = (current + MILISECONDS_IN_DAY-1) / MILISECONDS_IN_DAY;

or

days = Math.ceil((double) current / MILISECONDS_IN_DAY);

btw milli-seconds has two l's

Upvotes: 2

Achintya Jha
Achintya Jha

Reputation: 12843

cast to double.

days = (double)current / (double)MILISECONDS_IN_DAY;

Upvotes: 0

Related Questions