Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing exact real number arithmetic with PHP

What is fastest and most easy way of making basic arithmetic operations on strings representing real numbers in PHP? I have a string representing MySQL's DECIMAL value on which I want to operate and return the result to a database after that. I would like to avoid errors introduced by floating-point real number representation.

Is there some standard library like Python's decimal? Are there any FOSS libraries you can recommend?

Regards

like image 604
Dariusz Walczak Avatar asked Dec 21 '10 18:12

Dariusz Walczak


2 Answers

You could use the BC math functions:

http://www.php.net/manual/en/ref.bc.php

Or the GMP functions, although they seem to be integer only.

http://www.php.net/manual/en/ref.gmp.php

like image 80
GolezTrol Avatar answered Sep 30 '22 08:09

GolezTrol


You can use the bc_math extension, which works exactly how you ask (it's used for arbitrary precision numbers):

$num = '123.456';
$twoNum = bcadd($num, $num);
like image 22
ircmaxell Avatar answered Sep 30 '22 07:09

ircmaxell