[英]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: 之后,我将
$value_formated
值与另一个值进行比较,例如:
$another_value = 20.40;
if($value_formated <= $another_value)
{
//Error
}
else
{
//Proceed
}
But I receive the error A non well formed numeric value encountered . 但是我收到错误A格式不正确的数值 。
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)
. 请记住,我从客户端收到了
$value
变量的$value
,因此,这里可以存在任何内容,但是如果不符合if($value_formated <= $another_value)
,我将通过它。
combining @Hayden Schiff 's answer 结合@Hayden Schiff的答案
<?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). 逗号不是PHP中默认的小数点分隔符,这就是为什么只考虑整数部分的原因(因为逗号不被视为数字的一部分)。
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: 注意:例如,如果要从原始字符串中删除用作千位分隔符的点而不影响小数点分隔符,可以使用
strtr
代替str_replace
以避免循环替换:
$str = strtr('R$100.000.000,25', ['R' => '', '$' => '', ',' => '.', '.' => '']);
echo number_format($str, 2, ',', '.');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.