0

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).

3
  • replace the comma , to a dot . . You are comparing 10,20 <= 20.40 Commented Sep 14, 2016 at 2:27
  • @roullie they're working with floats, not strings Commented Sep 14, 2016 at 2:28
  • @roullie Alright, but the error remains and if I use $value_subs = floatval($value_subs); as mentioned in the answer below, I get 10.00, not 10.25 Commented Sep 14, 2016 at 2:32

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

That's nice, but this shows 20 instead 20.00. Is there a way to show with dot and zeros?
0

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, ',', '.');

1 Comment

Thank you for your solution, but I've already accepted roullie's answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.