PHP:依赖于语言环境的 float 到字符串转换

标签 php string casting locale

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

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

返回

string(5) "1.234"

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

string(5) "1,234"

为什么 PHP 在将 float 类型转换为字符串时使用语言环境?我怎样才能禁用它?我想让这个函数在所有机器上都返回 string(5) "1.234",而不管任何语言环境设置如何。

其次也是次要的:为什么 PHP 会忽略我机器上的 setlocale?

最佳答案

Why the heck does PHP use the locale when typecasting floats to strings?

这就是它的行为

How can I disable it?

你不能(据我所知)。

如果安装了 locale,则可以将 locale 设置为 en_US

I'd like to have this function return string(5) "1.234" on all machines, regardless of any locale settings.

您有多种选择:


$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.      */   

Secondly and less important: Why does PHP ignore the setlocale on my machine?

作为DevZer0评论说您可能没有安装语言环境。

关于PHP:依赖于语言环境的 float 到字符串转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17587581/

相关文章:

php - 从数据库检索到下拉列表的数据。用户选择选项然后将该值发送到数据库?

php - MySQL根据字段字数进行相关性搜索

string - 找到数组中第一个匹配的字符串?

python - Mysql 在一个查询中进行转换和比较?

php - 从 mysql 中类型转换数字数据在 PHP 中不起作用

c - 为什么变量变为零?

php - 查询结果的分页无法正常工作

php - 用php显示mysql表

visual-studio-2008 - Visual Studio 2008喜欢在我的代码中插入随机字符串

java - 两个内容相同的字符串会存储在同一个内存位置吗?