Note that there are some explanatory texts on larger screens.

plurals
  1. POcast from double to int is not always just dropping decimal part
    primarykey
    data
    text
    <p>I'm experimenting with the code I found here <a href="http://www.javaspecialists.eu/archive/Issue197.html" rel="nofollow noreferrer">The Java Specialists' Newsletter</a>.</p> <pre><code>public class MeaningOfLife { public static String findOutWhatLifeIsAllAbout() { int meaning = 0; for (int i = 0; i &lt; 10; i++) { for (int j = 0; j &lt; 20; j++) { for (int k = 0; k &lt; 300; k++) { for (int m = 0; m &lt; 7000; m++) { meaning += Math.random() + 1; } } } } return String.valueOf(meaning).replaceAll("0*$", ""); } public static void main(String[] args) { System.out.println(findOutWhatLifeIsAllAbout()); } } </code></pre> <p>The answer to the question "what does it print" seemed obvious once I realized that there is an implicit cast with the <a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.26.2" rel="nofollow noreferrer">compound assignment operator</a> +=.</p> <p>But it printed something like: 420000006 or 420000007, instead of (the expected) 420000000 (or "42", after removing trailing zeros).</p> <p>So that was showing that casting from double to int is not always just dropping the decimal part of the double as stated here: <a href="https://stackoverflow.com/questions/2143476/how-to-cast-a-double-to-an-int-in-java">How to cast a double to an int in Java?</a></p> <p>So I made some trials and here is an example of what I found:</p> <pre><code>System.out.println((int) (131070.99999999999)); // -&gt; 131070 System.out.println((int) (131071.99999999999)); // -&gt; 131071 System.out.println((int) (131072.99999999999)); // -&gt; 131073 !!! System.out.println((int) (131073.99999999999)); // -&gt; 131074 !!! System.out.println((int) (16382.999999999999)); // -&gt; 16382 System.out.println((int) (16383.999999999999)); // -&gt; 16383 System.out.println((int) (16384.999999999999)); // -&gt; 16385 !!! System.out.println((int) (16385.999999999999)); // -&gt; 16386 !!! </code></pre> <p>...So now I'm looking for an explanation for that behavior ???</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload