使用setlocale()不会影响PHP的数字转换 [英] Using setlocale() doesn't affect PHPs number conversions
问题描述
我有以下脚本:
<?php
$test = "2.5";
echo (float)$test;
echo "\n";
$r = setlocale(LC_ALL, "da_DK.UTF8");
setlocale(LC_ALL, NULL);
print_r(localeconv());
echo "\n";
echo (float)$test;
echo "\n";
echo (float)"2,5";
echo "\n";
?>
哪个生成以下输出:
2.5
Array
(
[decimal_point] => ,
[thousands_sep] => .
[int_curr_symbol] => DKK
[currency_symbol] => kr
[mon_decimal_point] => ,
[mon_thousands_sep] => .
[positive_sign] =>
[negative_sign] => -
[int_frac_digits] => 2
[frac_digits] => 2
[p_cs_precedes] => 1
[p_sep_by_space] => 2
[n_cs_precedes] => 1
[n_sep_by_space] => 2
[p_sign_posn] => 4
[n_sign_posn] => 4
[grouping] => Array
(
[0] => 3
[1] => 3
)
[mon_grouping] => Array
(
[0] => 3
[1] => 3
)
)
2,5
2
最后一行读取2
-我本来希望读取2,5
-并且据我在PHP文档中所看到的那样.
如果省略了对setlocale
的第二次调用,则localeconv()
的输出与丹麦语言环境不一致-出于我不清楚的原因.
The very last line which reads 2
- I would have expected that to read 2,5
- and as far as I can see on the PHP documentation, it should.
If the second call to setlocale
is omitted then the output of localeconv()
is inconsistent with the danish locale - for reasons that are unclear to me.
推荐答案
(float)"2,5"
等于2(注意逗号),而(float)"2.5"
等于2.5.原因可以在手册中阅读:
(float)"2,5"
equals 2 (note the comma) whereas (float)"2.5"
equals 2.5. The reason can be read in the manual:
如果字符串不包含任何字符.","e"或"E",并且数值适合整数类型限制(由PHP_INT_MAX定义),则字符串将被评估为整数.在所有其他情况下,它将被视为浮点数.
If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.
类型转换不受setlocale()
的影响.
这篇关于使用setlocale()不会影响PHP的数字转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!