Hello,

PHP gives me wrong calculation results. !?

Example, PHP says that:
(47,60*554,82)/100 = 263,7
The right result is: 264

My code:

function kurs_usd($value) { // in use (usd to dkk)
    $kurs = mysql_fetch_array(mysql_query("SELECT kurs, time FROM pvs.kurs WHERE id = 'usd'"));
        if(time() >= $kurs['time']) {
        $data = explode("\n", file_get_contents("http://www.nationalbanken.dk/_vti_bin/DN/DataService.svc/CurrencyRatesXML?lang=da"));
        for($i = 0; $i < count($data); $i++) {
            if(preg_match("/USD/i", $data[$i]) == 1) {
                $kursp = strip(str_replace(" ", "", str_replace("\" />", "", str_replace("<currency code=\"USD\" desc=\"Amerikanske dollar\" rate=\"", "", $data[$i]))));
            }  
        }
    $time = time() + 3600;
    mysql_query("UPDATE pvs.kurs SET `kurs` = '$kursp' WHERE id = 'usd'");
    mysql_query("UPDATE pvs.kurs SET `time` = '$time' WHERE id = 'usd'");
    }

    ////// This is where i tested the inputs, and there where no problems
    echo "aaa &nbsp;&nbsp;&nbsp;" . $kurs['kurs'] . "&nbsp;&nbsp;&nbsp; aaa";
    echo "aaa &nbsp;&nbsp;&nbsp;" . $value . "&nbsp;&nbsp;&nbsp; aaa";
    ////////////////////////////////////////////////////////////////////////

    return round(($value * $kurs['kurs']) / 100, 2);    
}

What is wrong?!?!?!?!??!? :-)

echo round(((47.60 * 554.82) / 100), 2);

Gives me 264.09, you're rounding on two decimals so it will never be 264, but it shouldn't give you 263.7 either.

However, if you do (47.60 * 554) / 100) (and not 554.82) you will get 263.704. So my guess is that by using the direct database value (perhaps it's a string and not a float) the conversion PHP makes is off because of the comma that's probably in there. You'll have to replace the , with a . first, then for safety use floatvar($string) or (float) $string to cast it, then use it in your calculation. Also, be careful if your database numbers have comma's as a thousand separator in them (but I'm unsure if that is common when the comma is also the decimal separator). If you do have thousand separators it would be safer to keep the numbers without comma's in your database and then use number_fomat for instance to make them readable.

Hi, this happens in Javascript and PHP when using float numbers, to avoid this problem you can use the BC Math library:

echo bcdiv(bcmul(47.60, 554.82), 100, 2);

Which returns 264.09, the third argument of bcdiv() is rounding to the second decimal. If you want 264 then remove the third argument:

echo bcdiv(bcmul(47.60, 554.82), 100);

For more information check this thread:

About BC Math: http://php.net/manual/en/intro.bc.php
In alternative consider also the GMP library: http://php.net/manual/en/intro.gmp.php

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.