# converting a double to an int

Brandi Love
Ranch Hand
Posts: 133
If I'm converting a double to an integer, does it just take off all the numbers beyond the decimal point? (for example if I converted 1.4235 to an integer, would I just get a result of 1)

Wayne L Johnson
Ranch Hand
Posts: 399
You are correct. It essentially does a truncate, not a round. So if you convert 1.999 to an int you'd still end up with 1. And you have to explicitly cast it or you'll get a compile error.
double dd = 1.995;
int ii = (int)dd; // correct
int jj = dd; // compile error
In the java.lang.Math class are several convenience methods for doing things like "floor()", "trunc()", "round()", etc., if you want to do something else.

Giselle Dazzi
Ranch Hand
Posts: 168
Hi, I also need to truncate a number, and I went and looked under java.lang.Math like you said and I cant find a trunc() method.
I see round, floor, ceil, but no trunc(), what do you guys have been using to truncate a double value ?

Wayne L Johnson
Ranch Hand
Posts: 399
That's what I get for quickly throwing up an answer w/out double-checking with the documentation. My bad: there is no "trunc()" method.
If you want to truncate a "double" value there are a couple of options:

This gives you the output:
DD1: 1234.5678
II1: 1234
DD2: 1234.0
DD2: 1234.56
So you can truncate and store the result as an "int" (such as "ii1"), or store the result as a double (such as "dd2"). Or you can truncate to two digits (such as in "dd3").
Because of the way in which real numbers are stored, you might truncate and instead of coming out with "1234.56" as here, you could get "1234.55999999999999". If you want to ensure you what gets printed out only has a certain number of digits, use the "java.text.DecimalFormat" class to do your formatting.
[ November 10, 2003: Message edited by: Wayne L Johnson ]

David Crossett
Ranch Hand
Posts: 102
You can also use the java.text.DecimalFormat class to 'truncate' a double. Look it up and if you need an example, say so and I'll post some.