Since double is bigger data type than int, it needs to be down-casted as shown below: The easiest way to convert a double to int in Java is by type casting but it works only when your requirement is just to get rid of anything after the decimal point. In this article, I'll show you a couple of examples to convert double to int in Java. You can also convert a double primitive variable to a Double wrapper object and then call the intValue() method to get a corresponding int value. If you need an int primitive value then you need to further cast long to int in Java. If you need 10 then you need to use Math.round() method to first round the double value to the nearest integer and then truncate decimals.Īs we have seen, while converting float to int, the Math.round() method is overloaded and the version which accepts double returns a long primitive value. Btw, typecasting doesn't do any rounding or flooring, which means if you have 9.999999 and while casting to int you are expecting 10 then you would be disappointed, casting will give you just 9. double is 64-bit primitive value and when you cast it to a 32-bit integer, anything after the decimal point is lost. Suppose you have a double primitive variable 4.444 and you want to convert it to the integer value 4, how do you that in Java? Since double is bigger data type than int, you can simply downcast double to int in Java.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |