Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

casting - Convert a big integer to a full string in PHP

I've been searching for a while now, but what I can find is not what I search for. I need to convert an integer value, that may be very huge, to a string. Sounds easy: "$var"? No, because this can lead to the E+ representation of the number.

<?php

$var = 10000000000000000000000000;
echo $var."
";
echo "'$var'
";
echo (string) $var."
";
echo strval($var);

?>

1.0E+25
'1.0E+25'
1.0E+25
1.0E+25

How can I make the output be 10000000000000000000000000 instead?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is not stored as an integer by PHP, but a float, this is why you end up with 1.0E+25 instead of 10000000000000000000000000.

It's sadly not possible to use that as an integer value in PHP, as PHP cannot save an integer of that size. If this comes from database then it will be a string and you can do with it whatever you want. If you store it elsewhere then store it as a string.

Your alternative is to store it as a float and take that into account at all times, though that requires additional conversions and handling in places.

It's also been suggested to use GNU Multiple Precision, but that's not enabled in PHP by default.

$int=gmp_init("10000000000000000000000000");
$string=gmp_strval($int);
echo $string;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...