maen
maen

Reputation: 187

Why use double instead of integer?

First things first: I come from php and want to widen my horizon with java! So I read some books. I saw that rounding a number is posible wit Math.round().

My question is as follows: If I want to round a number as a decimal, I have to use this code:

double number;
number = 1.111222;
number = Math.round(number*100.0) / 100.0;

or number = (digit) Math.round(number*100) / 100;

But why does

number = Math.round(number*100) / 100;

doesn't do the exact same thing???

Thx in advance,

Marc

Upvotes: 0

Views: 1234

Answers (4)

Würgspaß
Würgspaß

Reputation: 4820

Because Math.round returns a long. So the result of rounding (of type long) is divided by an int. Before division JVM converts both to long. See here for Java widening conversion rules.

Upvotes: 1

chancea
chancea

Reputation: 5968

If assuming that you mean to put a decimal point for that comma 1.111222

The problem is that 100 will cast the value to a long while 100.0 will cast it to a double. long's cannot have decimals but double's can.

Look at both cases:

Case 1 produces a double:

Math.round(1.111222*100.0) => Math.round(111.222) => 111
111/100.0 => 1.11

Case 2 produces a int long:

(I orignally thought int but was proven wrong by the output, the reason being Math.round(double) returns a long found here)

Math.round(1.111222*100) => Math.round(111) => 111
111/100 => 1 //truncated due to being a long

You can see this by running this code:

public static void main (String[] args)
{
    double number = 1.111222;

    System.out.println(Math.round(number*100.0)/100.0);
    System.out.println(Math.round(number*100)/100);

    Object a = Math.round(number*100.0)/100.0;
    Object b = Math.round(number*100)/100;

    System.out.println(a.getClass().getName());
    System.out.println(b.getClass().getName());

}

Which prints:

1.11
1
java.lang.Double
java.lang.Long

Upvotes: 3

Alan
Alan

Reputation: 3002

When you call Math.round(), the result is an integer value. When you divide two integers (e.g. / 100), Java will perform an integer division, throwing away the fractional part of the result.

When you divide an integer by a double (e.g. / 100.0), Java will first convert the integer to a double value, and then perform a floating point division, retaining the fractional part.

Upvotes: 0

K139
K139

Reputation: 3669

It's clear in javadoc.

 Returns the closest {@code int} to the argument, with ties rounding up.

So round(float) returns int, and round(double) returns long.

Upvotes: 1

Related Questions