Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract 1 from a large number in PHP

Tags:

php

I need to subtract 1 from the number 294867828828426241 in PHP. However when I do

$a = 294867828828426241 - 1;

I receive the floating point number 2.94867828828E+17. Which, when resolved by number_format() gives the original number.

How can i get the correct value, please?

This needs to be able to be able work with different numbers.

like image 304
Jack B Avatar asked Jan 28 '13 22:01

Jack B


1 Answers

If you have the BCMath extension you can use this:

$a = bcsub('294867828828426241', '1');

echo $a; // 294867828828426240

However, testing on my 64-bit server your code should work correctly. I'm not sure, but you can check to see if increasing the precision directive in your php.ini will make any difference. I have mine set at 14.

like image 86
cryptic ツ Avatar answered Oct 08 '22 21:10

cryptic ツ