0

Parsing a string value to a float value is not consistent in my PHP project. Altough I'm not changing my code and the values to parse are always the same I sometimes get a result with a comma and sometimes with a point.

The incoming value is for example: 35,59 Before parsing this value I first replace the comma by a point.

$value = '35,59';
$value = (float)str_replace(',', '.', $value);
var_dump($value);

When I now use this value in my insert query, this sometimes results in a bug because a comma is used. This is all a bit weird to me, has anyone experienced this before? How can I prevent this from happening?

Edit: I indeed forgot my quotes in this example, but I did use quotes in my code

4

1 回答 1

1
$value = 35,59;

问题是解析器无法将“,”识别为十进制分隔符。您的语言环境可能会以这种方式定义数字,但您必须以编程方式使用句点或将值声明为字符串。

$value = "35,59";
// or
$value = 35.59;

如果得到35,59,则必须对其进行硬编码,因为任何返回此值的数据源都会自动被视为字符串。

有关如何正确转换格式化字符串的信息,请参阅http://us2.php.net/numberformatter.parse 。

IE

$fmt = new NumberFormatter( 'sv_SE', NumberFormatter::DECIMAL );
$value = "35,59";
echo $fmt->parse($value); // 35.59

编辑 此外,您str_replace将因 X 数量的语言环境而失败,因为有些人通常使用“,”作为千位分隔符。

于 2013-11-12T15:10:09.570 回答