sark9012
sark9012

Reputation: 5747

Rounding a double

Hey guys, I am trying to round to 3 decimal places.

I used the following code.

this.hours = Round(hours + (mins / 60), 3);

But it's not working. Where have I gone wrong? Thanks

Upvotes: 0

Views: 2475

Answers (6)

user207421
user207421

Reputation: 311052

You can't. Doubles don't have decimal places, because they are binary, not decimal. You can convert it to something that does have decimal places, i.e. a base-ten number, e.g. BigDecimal, and adjust the precision, or you can format it for output with the facilities of java.text, e.g. DecimalFormat, or the appropriate System.out.printf() string.

Upvotes: -1

asela38
asela38

Reputation: 4654

try using like follow

this.hours = Round(hours + (((double)mins) / 60), 3); 

Upvotes: 0

aioobe
aioobe

Reputation: 421340

If mins is an integer, then mins / 60 will result in an integer division, which always results in 0.

Try changing from 60 to 60.0 to make sure that the division is treated as a floating point division.

Example:

int hours = 5;
int mins = 7;

// This gives 5.0
System.out.println(Math.round(1000 * (hours + (mins / 60  ))) / 1000.0);

// While this gives the correct value 5.117.           (.0 was added)
System.out.println(Math.round(1000 * (hours + (mins / 60.0))) / 1000.0);

Upvotes: 2

christian
christian

Reputation: 401

if mins is an integer you have to divide through 60.0 to get a floating number which you can round

Upvotes: 0

Michel
Michel

Reputation: 9440

You can use this function:

 public static double Round(double number, int decimals)
    {
    double mod = Math.pow(10.0, decimals);
    return Math.round(number * mod ) / mod;
    }

Upvotes: 5

Carlos Tasada
Carlos Tasada

Reputation: 4444

First thing is that all your variables are int so the result of your division is also an int, so nothing to Round.

Then take a look to: How to round a number to n decimal places in Java

Upvotes: 2

Related Questions