Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

convert
double
int
java

How to convert a double to int in Java

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Let’s say that the double variable x holds the value 3.6987 and needs to be converted to an int. There are two ways that this can be done:

  • All the digits after the decimal are lost and x holds the integer 33; this can be done using typecasting in Java.

  • The value is rounded off to the nearest integer (i.e.,3.6987 is rounded off to 44); this can be done using the Math.round() function in Java.​

svg viewer

1. Typecasting

Since double is a bigger data type than int, it needs to be down-casted. See the syntax below:

int IntValue = (int) DoubleValue;

Code

The code snippet below illustrates double to int typecasting in Java:

class DoubleToInt {
public static void main( String args[] ) {
double DoubleValue = 3.6987;
int IntValue = (int) DoubleValue;
System.out.println(DoubleValue + " is now " + IntValue);
}
}

2. Using Math.round()

Math.round() accepts a double value and converts it into the nearest long value by adding 0.50.5 to the value and truncating its decimal points. The long value can then be converted to an int using typecasting.

The syntax for the Math.round() function is:

long Math.round(double DoubleValue);

The code snippet below illustrates the usage of Math.round() when converting a double data type to an int in Java:

class DoubleToInt {
public static void main( String args[] ) {
double DoubleValue = 3.6987;
int IntValue = (int) Math.round(DoubleValue);
System.out.println(DoubleValue + " is now " + IntValue);
}
}

RELATED TAGS

convert
double
int
java
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring