Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
433 views
Welcome To Ask or Share your Answers For Others

1 Answer

number_format(), as stated by the PHP manual, converts a float into a string with the thousands groups with commas.

$number = '1562798794365432135246';
var_dump($number); // string(22) "1562798794365432135246"
var_dump(number_format($number)); // string(29) "1,562,798,794,365,432,233,984" 

If you're trying to cast a string to an integer, you can do so like this:

$number = (int) $number;

However, be careful, since the largest possible integer value in PHP is 2147483647 on a 32-bit system and 9223372036854775807 on 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 $number to 2147483647 rather than the value you intend!

The 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...