0

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.

odran037
  • 271
  • 5
  • 17
  • 1
    number_format — Format a number with grouped thousands. so what is incorrect? – Rakesh Sharma Sep 18 '14 at 05:03
  • What do you expect from the number format? It's to format the number with decimal places, thousand places, and the thousand separator. Please refer to the php manual. – Nimeshka Srimal Sep 18 '14 at 05:08
  • 1
    This question is not about commas, please read again. What they are confused about is why the output number is different from what they input. – Hanky Panky Sep 18 '14 at 05:12

2 Answers2

2

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

Community
  • 1
  • 1
Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
  • Thank you for your reply. This is exactly what I figured. Also thank you for the links to the manual. I should have looked there first but nonetheless, thanks. – odran037 Sep 19 '14 at 03:12
1

You can't pass large numbers to the number_format() function. If you just need to format the number, you can write your own function to separate the numbers with a comma taking 3 by 3.

Reason is that if you check the manual, the number format takes the first parameter as a float. You need to have a good understanding about float, and ints to understand why it happens.

Here is something interesting I found in SO, it is same as your question, and it has a good answer. Please check it.

Why is my number value changing using number_format()?

Nimeshka Srimal
  • 8,012
  • 5
  • 42
  • 57