How to manage number values with points?

Issue

$val represents 1,949.58 from my sql

 $sold = 50;
    if ($val>$sold){
    echo "true";
    }
    else
    {
    echo "false";
    }

I get false. somehow 50 is bigger than 1,949.58 and this because of the ‘,’ sign. I need some advices on how to manage this right. Thx

Solution

$val is interpreted by php to be a string. When doing the comparison, it’s doing a string compare so you aren’t going to get the results you expect.

You need to force them to be a floating point type. Look at http://php.net/manual/en/function.floatval.php Specifically the comments on that function.

Something like this should work:

function floatvalue($value) { 
     return floatval(preg_replace('#^([-]*[0-9\.,\' ]+?)((\.|,){1}([0-9-]{1,2}))*$#e', "str_replace(array('.', ',', \"'\", ' '), '', '\\1') . '.\\4'", $value)); 
} 

Answered By – NotMe

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published