Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert double to string in php

Tags:

php

I've a simple question.

I've this 7310093341976450848 number which I needed to echo.But when I echo it gives me this 7.3100933419765E+18.

I tried

echo (string)$data;
to cast it to string and then print it but it's still giving the same result.

The number is initially of type double.

like image 853
Mj1992 Avatar asked Jul 07 '12 17:07

Mj1992


1 Answers

I've this 7310093341976450848 number which I needed to echo.
The number is initially of type double.

Because of the floating point representation used in PHP, once it's stored as a double, you cannot print out that exact number anymore.

This is one of the (many) ways to print out the value:

printf("%.0f", $data);
echo number_format($data, 0, '', '');

If you don't want to lose precision, store it as a string, or use one of the arbitrary precision libraries: BC Math / GMP.

like image 79
Karoly Horvath Avatar answered Sep 20 '22 19:09

Karoly Horvath