简体   繁体   中英

PHP number_format error

I have a string like:

R$10,25

I need to convert it to:

10.25

I'm trying with:

$value = 'R$10,20';
$value_subs = str_replace(array('R', '$'), '', $value);
$value_formated = number_format($value_subs, 2, ',', '.');

After I will compare the $value_formated value with another to proceed the code, like:

$another_value = 20.40;
if($value_formated <= $another_value)
{
    //Error
}
else
{
    //Proceed
}

But I receive the error A non well formed numeric value encountered .
How to achieve this? Having in mind that I receive the value of the $value variable from the client, so, anything can be present here, but I just will pass it if aren't according with if($value_formated <= $another_value) .

combining @Hayden Schiff 's answer

<?php

    $value = 'R$10,20';
    $value_subs = str_replace(array('R', '$',','), array('','','.'), $value);
    $value_formated = floatval($value_subs);

    $another_value = 20.40;
    if($value_formated <= $another_value)
    {
        echo "Less or equal";
    }
    else
    {
        echo "Greater";
    }

replace , to a . then parses the result to a float

The comma isn't the default decimal separator in PHP, that's why only the integer part is taken in account (since the comma isn't seen as a part of a number).

To solve the problem, you need to replace this comma with a dot.

A way:

$str = strtr($str, ['R' => '', '$' => '', ',' => '.']);
echo number_format($str, 2, ',', '.');

Note: using strtr in place of str_replace may be interesting to avoid a circular replacement if, for example, you want to remove dots used as thousand separator from the original string without to affect the decimal separator:

$str = strtr('R$100.000.000,25', ['R' => '', '$' => '', ',' => '.', '.' => '']);
echo number_format($str, 2, ',', '.');

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