+ 3

While casting how does converting from double to integer rounds off to lower value?

Eg: 1.5 should round off to 2 and 2.65 should be rounded off to 3 Making the sum to be 5(2+3) but the int(x) and int(y) takes only 1+2 giving a sum 3. Can someone explain me how?

18th May 2017, 7:28 AM
VIBIN.J
VIBIN.J  - avatar
2 ответов
+ 8
using (int)x will return the integer part of x without the fraction part, i.e the the first integer < x. if you want to get the first integer > x you must use Math.ceil(x). the below example show the difference between casting (int)x and the use of Math.ceil(x): double x = 1.3; int y, z; y = (int)x; z = (int)Math.ceil(x); System.out.print(y); System.out.print(z); // out put will be // y = 1 // z = 2
18th May 2017, 7:56 AM
Mohammad Dakdouk
Mohammad Dakdouk - avatar
+ 5
you can use built in function math.round(double) to convert 1.5 to 2 and then sum it
18th May 2017, 7:53 AM
Manikandan
Manikandan - avatar