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
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
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 .
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
.
When you call Math.round(), the result is an integer value. When you divide two integers (eg / 100), Java will perform an integer division, throwing away the fractional part of the result.
When you divide an integer by a double (eg / 100.0), Java will first convert the integer to a double value, and then perform a floating point division, retaining the fractional part.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.