Thursday, January 23, 2025
HomeQ&AConvert Double to Integer in Java

Convert Double to Integer in Java

In Java, you can convert a double to an int using type casting or by using the Math.round() method depending on how you want the rounding to behave. Here are a few examples:

1. Type Casting (Truncating Decimal)

This method simply drops the decimal part and keeps the integer part.

double myDouble = 9.99;
int myInt = (int) myDouble; // myInt will be 9

2. Using Math.round() (Rounding to the Nearest Integer)

If you want to round the double value to the nearest integer, you can use Math.round(). This method returns a long, so you’ll need to cast it to an int.

double myDouble = 9.99;
int myInt = (int) Math.round(myDouble); // myInt will be 10

3. Using Math.floor() or Math.ceil() (Rounding Down or Up)

If you want to round down (always to the lower integer) or up (always to the higher integer), you can use Math.floor() or Math.ceil() respectively, followed by casting to int.

double myDouble = 9.99;
int myIntFloor = (int) Math.floor(myDouble); // myIntFloor will be 9 (rounds down)
int myIntCeil = (int) Math.ceil(myDouble);   // myIntCeil will be 10 (rounds up)

Summary

  • Type casting is the most straightforward and drops the decimal part.
  • Math.round() rounds to the nearest integer.
  • Math.floor() and Math.ceil() give you control over rounding down or up respectively.
See also  What Are Absolute Coordinates?

 

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Does Wag Mean Slag?

What does the Term K9 mean?

Is Killua a Boy or a Girl?

Recent Comments

0
Would love your thoughts, please comment.x
()
x