Search code examples
javaphptypesnumbersprimitive

Java - PHP Number-Type Mix Up (9966006699)


I was doing some stuff with palindromes:

This number 9966006699 has been giving me problems. It's a product of 99979 and 99681

99979 * 99681 = 9966006699

I ran that in PHP

$i = 99979 * 99681;
echo $i;
var_dump($i);

Outputs

9966006699 float(9966006699)

So in PHP the product is obviously a float data type. But in Java it's different as seen below :

This

 public static void main(String[] args) {

      float f = 99979 * 99681;
       System.out.println(f);

       long o = 99979 * 99681;
       System.out.println(o);

       double d = 99979 * 99681;
       System.out.println(d);

       int i = 99979 * 99681;
       System.out.println(i);


   }

Outputs

1.37607206E9
1376072107
1.376072107E9
1376072107

Google's calculator gives the right thing

I'm lost, why is Java giving the wrong output? and Does it have anything to do with the E9 stuff behind the float and double types? Help. Thanks


Solution

  • The numbers 99979 and 99681 are both int's. The multiplication expression is therefore an int expression too. The maximum value of an int expression is 2147...... Your value 9966006699 is way above that. Hence you have fallen in the realms of the strange behaviour that you get from modulo-n arithmetic. (That is, you have fallen victim to the C-family languages' version of the Y2K problem.)

    Try this :

           long o = (long)99979 * 99681;
           System.out.println(o);