Search code examples
phpnumber-formatting

PHP number_format displaying incorrectly


New to programming and taking a PHP course. I wrote a very small program to test out the number_format function. Here is my code:

$num = 9876543210123456789; 
$result = number_format($num);
echo = $result;

The output is: 9,876,543,210,123,456,512

I'm sure it has something to do with the length of $num. But haven't been able to find the exact explanation/reason why this happens.


Solution

  • You're seeig a different number because the number you have provided is large enough to cause an overflow on your system. Try with a smaller number

    <?php
    $num = 9876543210123; 
    $result = number_format($num);
    echo  $result;                    // will show as expected, with formatting
    

    Even if you don't use number_format on that number, your number will still cause overflow. Try this

    $num = 9876543210123456789; 
    echo  $num;   // not what you see above
    

    Also see:

    What's the maximum size for an int in PHP?

    PHP Integers and Overflow