1

I am getting a couple of values from a database query. The values that I am getting look like:

10.810000000000000497 and I want to use just '10.81'.

or

2.6899999999999999467 and I want to use just 2.69

when using ini_set('precision', 20);

How how should I use this values with bcadd() for example? As I just want to add 10.81 + 2.69?

Valentin Despa
  • 40,712
  • 18
  • 80
  • 106
  • Use [round](http://php.net/manual/en/function.round.php) or [number_format](http://php.net/manual/en/function.number-format.php) to acomplish what you want. – Peon Jan 22 '13 at 12:42
  • The problem I am facing involves multiple variables what I am getting from the database. This variables get added, subtracted, multiplied etc. In most of the cases it works fine, but in some cases somehow the error propagates and I am NOT receiving the expected results (usually one cent missing). – Valentin Despa Jan 22 '13 at 12:48

1 Answers1

1

The php BC_ functions has another option: scale.

$num1 = 10.810000000000000497;
$num2 = 2.6899999999999999467;
$result = bcadd($num1, $num2, 2);
echo $result; // 13.50

If you want to use it several times you may use bcscale() and such you won't need to specify the third option each time you use it:

bcscale(2);
$num1 = 10.810000000000000497;
$num2 = 2.6899999999999999467;
$result = bcadd($num1, $num2);
echo $result; // 13.50
HamZa
  • 14,671
  • 11
  • 54
  • 75