简体   繁体   中英

Converting number to string and then comparing in php

EDIT: Converted to using round which returns a float

I am converting am rounding a number to 2 decimals using round function

My question is about this line of code below:

Could their be rounding errors or unexpected behavior that could cause this condition to be true when it should not be?

if ($cc_amount > $total)

FULL CODE:

    $cc_amount = round($this->sale_lib->get_payment_total('credit'),2);
    $total = round($this->sale_lib->get_total(),2);

    //Since they are floats could there be rounding errors?
    if ($cc_amount > $total)
    {
        $this->_reload(array('error' => 'Credit card payment is greater than total');
    }

It's a little confusing as to what you are doing.

When comparing strings it could grab each character's ascii code and compare them one at a time from the left most character to the right so something like 823 > 2015.

If I were to compare I'd keep them in number format and calculate each amount given approximately like so.

function to_decimals($number, $decimals = 2)
{
    if (is_numeric($number))
    {
        $updown = (10^$decimals)
        return round(($number * $updown))/$updown;
    }
    else
    {
        return -999999;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM