How to Convert Double to Int in Java


In addition to allowing programmers to define any class they need, the Java programming language has built-in support for some simple numeric and string types. Those types include "int" for integers and "double" for double-precision, floating-point numbers. You can convert a double value to an int; however, because that implies losing information -- the fractional part, that cannot be represented by an int -- this conversion must be explicitly coded in your program.

  • Store the double value in a variable of class "double" as follows:

    double inputValue = 3.14159;

  • Declare an int variable to hold the result of the conversion:

    int outputValue;

  • Call the library method intValue() to perform the conversion:

    outputValue = Double.intValue(inputValue);

    Variable "outputValue" will hold the truncated (that is, rounded down to the nearest integer) value of "inputValue."


Promoted By Zergnet


Related Searches

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!