The following code gives me two different outputs:
$number = '1562798794365432135246'; echo $number; echo number_format($number);
Can anyone explain this?
EDIT: forgot to mention, the above gives me "1562798794365432135246 1,562,798,794,365,432,233,984". Note the last six digits are completely different for no obvious reason (all i was asking it to do was insert thousand separators).
number_format(), as stated by the PHP manual, converts a float into a string with the thousands groups with commas.
If you're trying to cast a string to an integer, you can do so like this:
However, be careful, since the largest possible integer value in PHP is
2147483647on a 32-bit system and
9223372036854775807on a 64-bit system. If you try to cast a string like the one above to int on a 32-bit system, you'll assign
2147483647rather than the value you intend!
number_format()function takes a float as an argument, which has similar issues. When you pass a string as an argument to
number_format(), it is internally converted to a float. Floats are a little more complicated than integers. Instead of having a hard upper bound like an integer value, floats progressively lose precision in the least significant digits, making those last few places incorrect.
So, unfortunately, if you need to format long strings like this you'll probably need to write your own function. If you only need to add commas in the thousands places, this should be easy - just use strlen and substr to get every set of three characters from the end of string and create a new string with commas in between.