Home >php教程 >php手册 >PHP浮点数显示和转成字符串

PHP浮点数显示和转成字符串

WBOY
WBOYOriginal
2016-06-21 08:52:322128browse

  你可能会觉得PHP中将浮点数(float)转成字符串非常简单, 但是, 常用的方法隐藏着严重的bug. 因为, PHP在处理浮点数时有非常不合理的做法, 会有精度丢失. 经研究, 其实是PHP在显示浮点数时的问题, 也可以说是BUG. PHP内置的echo, var_dump, json_encode, 字符串拼接等函数(指令)在显示浮点数时都有问题, 导致精度丢失.

  

   $a = 1315537636.338467;

   printf("%f", $a); echo "\n";

   echo $a . "\n";

   echo $a; echo "\n";

  ?>

  结果

  1315537636.338467

  1315537636.3385

  1315537636.3385

  也就是说, 用PHP最顺手的方法将浮点数转成字符串或者显示是不行的, 必须使用printf/sprintf将浮点数转成字符串.



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn