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
468 views
in Technique[技术] by (71.8m points)

printf - Why does PHP's sprintf not round 5s reliably?

I was relying on sprintf('%0.1f', 2.25) === '2.3' but it turns out it comes in at 2.2!

In fact it seems random:

php > for ($j=0;$j<=10;$j++) { printf( "%s -> %0.1f
",$j+ 0.05, $j+0.05); } 
0.05 -> 0.1 // Up, as expected
1.05 -> 1.1 // Up, as expected
2.05 -> 2.0 // Down!
3.05 -> 3.0 // Down!
4.05 -> 4.0 // Down!
5.05 -> 5.0 // Down!
6.05 -> 6.0 // Down!
7.05 -> 7.0 // Down!
8.05 -> 8.1 // Up, as expected
9.05 -> 9.1 // Up, as expected

Have I completely missed the point? I feel like a rug is being pulled away from under me and that all I learnt at school is wrong...! Surely a function to round numbers should do it consistently? (I note that round($n, 1) works as expected.)

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You should be using round

http://php.net/manual/en/function.round.php

round(2.25, 2) === floatval('2.3')

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

2.1m questions

2.1m answers

60 comments

57.0k users

...