Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting double to integer in Java

People also ask

Can you go from double to int?

round() method converts the double to an integer by rounding off the number to the nearest integer. For example – 10.6 will be converted to 11 using Math. round() method and 1ill be converted to 10 using typecasting or Double. intValue() method.

What happens when you cast a double to an int Java?

As we know double value can contain decimal digits (digits after decimal point), so when we convert double value with decimal digits to int value, the decimal digits are truncated.


is there a possibility that casting a double created via Math.round() will still result in a truncated down number

No, round() will always round your double to the correct value, and then, it will be cast to an long which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.

Here are the docs from Math.round(double):

Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:

(long)Math.floor(a + 0.5d)

For the datatype Double to int, you can use the following:

Double double = 5.00;

int integer = double.intValue();

Double perValue = 96.57;
int roundVal= (int) Math.round(perValue);

Solved my purpose.