Home > Backend Development > PHP Tutorial > 关于printf格式化输出问题

关于printf格式化输出问题

WBOY
Release: 2016-06-23 13:35:48
Original
908 people have browsed it

$a = 123.666;   
printf("%.2f", $a);
$b = 10.85;
print("
");
printf("%.1f",$b);


为什么结果是
123.67
10.8 
前一个四舍五入了,后一个没有?


回复讨论(解决方案)

printf("%.1f %.16f", 10.85, 10.85); //10.8 10.8499999999999996
浮点数 10.85 在机器中实际保存为 10.8499999999999996
所以取一位小数时是 10.8

其实这是不必纠结的事情,在计算机基础课程中你就已经学习过浮点数的表示和精度
如果你需要高精度运算,请使用 php 提供的 BC、gml 扩展

明白了,非常感谢!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template