php 在php中将浮点数转换为字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6876666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:31:12  来源:igfitidea点击:

Convert float to string in php?

phpstringfloating-pointtype-conversion

提问by tweety

Like:

喜欢:

float(1.2345678901235E+19) => string(20) "12345678901234567890"

浮动(1.2345678901235E+19)=>字符串(20)“12345678901234567890”

Can it be done?

可以做到吗?

(it's for json_decode...)

(它用于 json_decode ...)

回答by Karoly Horvath

echo number_format($float,0,'.','');

note: this is for integers, increase 0 for extra fractional digits

注意:这是整数,额外的小数数字增加 0

回答by lubart

$float = 0.123;
$string = sprintf("%.3f", $float); // $string = "0.123";

回答by Anthony

It turns out json_decodeby default casts large integers as floats. This option can be overwritten in the function call:

事实证明json_decode,默认情况下将大整数转换为浮点数。这个选项可以在函数调用中被覆盖:

$json_array = json_decode($json_string, , , 1);

I'm basing this only on the main documentation, so please test and let me know if it works.

我只基于主要文档,所以请测试并让我知道它是否有效。

回答by Alnitak

A double precision floating point number can only contain around 15 significant digits. The best you could do is pad the extra digits out with zeroes.

双精度浮点数只能包含大约 15 个有效数字。你能做的最好的事情就是用零填充额外的数字。

回答by Astrotim

I solved this issue by passing the argument JSON_BIGINT_AS_STRINGfor the optionsparameter.

我通过传递参数JSON_BIGINT_AS_STRINGoptions参数解决了这个问题。

json_decode($json, false, 512, JSON_BIGINT_AS_STRING)

json_decode($json, false, 512, JSON_BIGINT_AS_STRING)

See example #5 in the json_decode documentation

请参阅json_decode 文档中的示例 #5