5

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

Dariusz Walczak
  • 4,848
  • 5
  • 36
  • 39
  • BC Math module is a major step in the right direction for me (thank you!), but it's not perfect (so or so I didn't found it myself), because If I understand things correctly, I have to specify precision of the result explicitly. This may be a problem If I don't know the precision of input numbers - I will have to parse strings and calculate it manually. For now, I will use the BC module (thank you, once again) but maybe there are more flexible options? – Dariusz Walczak Dec 21 '10 at 18:51
  • 1
    You can set the precision once using `bcscale()`. You will need a precision because numbers are represented as floating points. 1/3 will return an infinite number of digits, so these operations need a certain precesion, even with strings. – GolezTrol Dec 21 '10 at 18:58
  • Nitpick: It's not possible to do *exact* arithmetic with real numbers in any known computing platform, since true real numbers (in the mathematical sense) cannot be represented exactly with any finite number of bits. You can define exactness to a certain number of decimal places when representing values in base-10 notation, but you must define a finite limit. – Daniel Pryden Dec 21 '10 at 18:59
  • 1
    I know that I can't always represent the exact value. Sometimes the result precision could however be calculated - in case of multiplication (sum of precisions) or in case of addition (greater precision). If the function doesn't do it for me and I don't know the precision, I have to calculate it, what isn't very comfortable :) – Dariusz Walczak Dec 21 '10 at 19:19

2 Answers2

5

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

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
  • FYI, BCMath is easier to use, but it doesn't scale very well. GMP is a lot trickier to work with as it only supports integers, meaning you'll have to implement your own decimal support on top of it (for example using an additional variable to indicate how many decimal places you should move left or right to get the actual value), but it has much better performance – GordonM Dec 19 '16 at 09:34
3

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);
ircmaxell
  • 163,128
  • 34
  • 264
  • 314