Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP gives incorrect results when formatting long numbers

I am working with huge numbers for website purposes and I need long calculation. When I echo a long number I don't get the correct output.

Example

// A random number
$x = 100000000000000000000000000;

$x = number_format($x);
echo "The number is: $x <br>";
// Result: 100,000,000,000,000,004,764,729,344 
// I'm not getting the value assigned to $x
like image 991
deerox Avatar asked Feb 03 '16 06:02

deerox


People also ask

What is number format PHP?

The number_format() function is an inbuilt function in PHP which is used to format a number with grouped thousands. It returns the formatted number on success otherwise it gives E_WARNING on failure. Syntax: string number_format ( $number, $decimals, $decimalpoint, $sep )

How do you count the length of a number in PHP?

PHP strlen() Function It takes a string as a parameter and returns its length. It calculates the length of the string including all the whitespaces and special characters. Syntax: strlen($string);


2 Answers

Your number is actually too big for php standard integers. php uses 64 bit integers which can hold values within range -9223372036854775808 (PHP_INT_MIN) to +9223372036854775807 (PHP_INT_MAX).

Your number is about 87 bits long which simply is too much.

If you really need such big numbers you should use the php BC math types, explained in the manual: http://php.net/manual/en/ref.bc.php

If you just want to format a string formed like a huge number then use something like this:

function number_format_string($number) {
    return strrev(implode(',', str_split(strrev($number), 3)));
}

$x = '100000000000000000000000000';

$x = number_format_string($x);
echo "The number is: $x\n";

// Output: The number is: 100,000,000,000,000,000,000,000,000

Edit: Added strrev() to function because the string needs to be reversed before splitting it up (thanks to @ceeee for the hint). This ensures that the delimiter is placed at right position when length of input is not divisible by 3. Generated string needs to be reversed afterwards again.

Working example can be found at http://sandbox.onlinephpfunctions.com/code/c10fc9b9e2c65a27710fb6be3a0202ad492e3e9a

like image 182
maxhb Avatar answered Oct 19 '22 22:10

maxhb


answer @maxhb has bug. if the input is '10000000000000000000000' the out put would be:

The number is: 100,000,000,000,000,000,000,00

Which is incorrect. So try below code:

function number_format_string($number, $delimeter = ',')
{
    return strrev(implode($delimeter, str_split(strrev($number), 3)));
}

$x = '10000000000000000000000';

$x = number_format_string($x);
echo "The number is: $x\n";

// Output: The number is: 10,000,000,000,000,000,000,000
like image 32
Ceeee Avatar answered Oct 19 '22 22:10

Ceeee