gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 12:57:49 25 4
gpt4 key购买 nike

我坐在一台有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com