ryantxr
ryantxr

Reputation: 4219

Floating point subtraction issue in PHP

This is a very simple issue to duplicate. I am doing a simple subtraction using floating point numbers. As you can see from the code below and the corresponding output, the calculation is not correct.

(php 5.6.6 on OSX El Capitan)

<?php

    $bal = 20017.1;
    $amt = 20000;
    $newbal = $bal - $amt;

    print_r(compact('bal', 'amt', 'newbal'));
    echo "\n";

As you can see from this output, $newbal is not correct.

Array
(
    [bal] => 20017.1
    [amt] => 20000
    [newbal] => 17.099999999999
)

Upvotes: 0

Views: 57

Answers (2)

sansig
sansig

Reputation: 81

You need to use functions to get accurate results with floating point numbers in PHP. Try using https://www.php.net/manual/en/ref.bc.php specifically the bcsub function, and explicitly tell it how many decimal places of accuracy you want.

Upvotes: 0

jszobody
jszobody

Reputation: 28911

For an explanation of why this is happening, see here:

http://floating-point-gui.de/

If you know in advance the precision you need, one simple solution is to use the bcsub() method:

$bal = 20017.1;
$amt = 20000;
$newbal = bcsub($bal,$amt,1); // 17.1

Working example: https://3v4l.org/PZ4qS

Upvotes: 3

Related Questions