Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

php - Why is my number value changing using number_format()?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...