开发者

PHP's floatval is not locale aware

I find that PHP's string to float conversion is not locale aware. If I setlocale() to a locale where the decimal point is a comma, floatval fails to parse "3,14". I find this surprising especially since the opposite conversion - float to string - is locale aware and outputs the comma.

<?php
setlocale(LC_ALL, "Norwegian", "no");
$localeconv = localeconv();
echo "decimal_point is `" . $localeconv['decimal_point'] . "'<br/>";
print "float to string: " . 3.14 . "<br/>"; //  <-- Outputs "开发者_C百科3,14" CORRECT
print "string to float: " . floatval("3,14"); // <-- Outputs "3" INCORRECT
?>

The output I get is the following:

decimal_point is `,'
float to string: 3,14
string to float: 3

This is with PHP 5.3.6 on Windows. Is this the intended behaviour? Does PHP on Unix give the same result?


There is a locale aware function in The PHP Manual

<?php
function ParseFloat($floatString){
    $LocaleInfo = localeconv();
    $floatString = str_replace($LocaleInfo["mon_thousands_sep"] , "", $floatString);
    $floatString = str_replace($LocaleInfo["mon_decimal_point"] , ".", $floatString);
    return floatval($floatString);
}
?>

This is safer than simply replacing commas with dots as that would break things for some locales.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜