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.
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 ?
Giselle Dazzi<br />SCJP 1.4
Wayne L Johnson
Joined: Sep 03, 2003
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 ]