简体   繁体   English

在PHP中将大数字转换为可用字符串

[英]Converting large number into a usable string in PHP

I am getting data from an API and it includes a long number, for example: 7979798798798798798798797987 . 我从API获取数据,它包含一个长数字,例如: 7979798798798798798798797987 I need to put this number into a URL so the variable doesn't need to be a number but I do need it to stay intact precisely. 我需要将这个数字放入一个URL,这样变量不需要是一个数字,但我确实需要它保持完整。 At the moment PHP is automatically converting the large number into scientific notation. 目前PHP正在自动将大数字转换为科学记数法。 I have tried all these things like sprintf and trying to cast it as a string but it's not working for me. 我已经尝试了所有这些东西,比如sprintf,并尝试将其作为一个字符串,但它不适合我。

Here's a demo: 这是一个演示:

$myvar = 7979798798798798798798797987; //can't change this as this is from api

echo $myvar; // needs to print out 7979798798798798798798797987

If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead (which is what you have) of int but float have a limited precision of around 14 digits. 如果PHP遇到一个超出整数类型边界的数字,它将被解释为一个浮点(而不是你所拥有的)int但float的精度有限,大约为14位数。

If the number is less than 14 digits, you can use sprintf('%0.0f',$number) ; 如果数字少于14位,您可以使用sprintf('%0.0f',$number) ;

In your case, you would need to work from your source data (json), as there is no way you can produce an exact representation of that number from its current form (float). 在您的情况下,您需要使用源数据(json),因为您无法从其当前形式(浮点数)生成该数字的精确表示。

you can use the JSON_BIGINT_AS_STRING options in json_decode 您可以使用JSON_BIGINT_AS_STRING中的JSON_BIGINT_AS_STRING选项

Sample Test Code 样本测试代码

<?php
$json = '{"number":7979798798798798798798797987, "data":"some other data"}';
$output=json_decode($json, false, 512, JSON_BIGINT_AS_STRING);
echo $output->number; \\output 7979798798798798798798797987
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM