number_format() Is this a bug?

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

number_format() Is this a bug?

Post by Benjamin »

This was creating a lot of problems for me today while trying to track down errors in 8 byte (64 bit) bitmaps.

Code: Select all

 
echo "18446744073709551615 = " . number_format('18446744073709551615', 0, '', '') . "\n";
 
Outputs:
18446744073709551615 = 18446744073709551616
:( Heads up I guess.

PHP Version 5.2.6
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: number_format() Is this a bug?

Post by Chris Corbyn »

Floating point errors probably. Very odd though.
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Re: number_format() Is this a bug?

Post by Ambush Commander »

The string is being cast into a float, and losing precision. This is obvious with a printf:

Code: Select all

$v = (float) '18446744073709551615';
printf('%f', $v); // 18446744073709551616.00000027
Use BCMath to get around this.
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Re: number_format() Is this a bug?

Post by Maugrim_The_Reaper »

It's a big integer - way past the 32bit limit. So it's a float, not an integer. Like AC said, you need BCMath, or preferably GMP (it's a great deal faster than BCMath).
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: number_format() Is this a bug?

Post by Benjamin »

Yeah it's the largest unsigned 64 bit integer I believe. I ended up using the gmp family of functions. Apparently that's only (64 bit) number that I couldn't accurately reproduce on a 64 bit processor.
Post Reply