PHP:依赖于区域设置的浮点到字符串转换


PHP: locale-dependent float to string cast

我坐在一台带有en_US语言环境和这段PHP代码的机器上

setlocale(LC_ALL,'de_DE.utf8');
var_dump((string)1.234);

返回

string(5) "1.234"

而在我同事的机器上,它的语言环境是德语,它返回

string(5) "1,234"

PHP为什么在类型转换为字符串时使用区域设置?如何禁用它?我希望这个函数在所有机器上返回字符串(5)"1.234",而不考虑任何区域设置。

第二个也是不那么重要的问题:为什么PHP忽略了我机器上的setlocale?

PHP为什么在类型转换为字符串时使用区域设置?

就是这样

如何禁用它?

你不能(据我所知)。

如果安装了语言环境,则可以将语言环境设置为en_US

我想让这个函数返回字符串(5)";1.234〃;在所有机器上,无论任何区域设置如何。

你有几个选择:


$num = 1.234; 

/* 1 - number format                            */
$str = number_format( $num, 3, '.', '' );
       
/*     you get exacly the number of digits      *
 *     passed as 2nd parameter.  Value  is      *
 *     properly rounded.                        */

/* 2 - sprintf                                  */
$str = sprintf( '%.3F', $num );
/*     you get exacly the number of digits      *
 *     specified bewtween `.` and `F`.          *
 *     Value is properly rounded.               */

/* 3 - json encode                              *
 *     optionally setting serialize_precision   */
ini_set( 'serialize_precision', 3 );
$str = json_encode( (float) $num );
/*     you get  -AT MOST-  the  number  of      *
 *     digits   as   per  language  option      *
 *     `serialize_precision`                    *
 *     If the number  can  be  represented      *
 *     with less digits  without  loss  of      *
 *     precision then trailing zeroes  are      *
 *     trimmed.                                 *
 *     If  `serialize_precision`  is  `-1`      *
 *     then all the available decimals are      *
 *     written.                                 *
 *     Note that altering the language opt      *
 *     affect all foat serialization funcs      *
 *     so you may want to set it  back  to      *
 *     its   previous  value   after   the      *
 *     conversion.                             *
 *     Value is  properly  rounded  unless       *
 *     `serialize_precision` is set to -1.      */   

第二个也是不那么重要的问题:为什么PHP忽略了我机器上的setlocale?

正如DevZer0所评论的,您可能没有安装区域设置。