Help us understand the problem. What is going on with this article?

PHP sprintfで小数点の桁数表示についてメモ

More than 3 years have passed since last update.

会社で話題になったので

小数点の桁数を指定して四捨五入する場合roundを使えばいいと思っているけど
sprintfでも行えるらしいが、挙動が自分の認識している四捨五入となんか違うのでメモ

roundの場合

round.php
<?php

echo "round(23.555,1)だと";
echo round(23.555,1);
echo "\n";

echo "round(23.555.2)だと";
echo round(23.555,2);
echo "\n";

実行結果

-sh-4.1$ php round.php 
round(23.555,1)だと23.6
round(23.555.2)だと23.56

sprintfの場合

sprintf.php
<?php

    $syo = 23.555;
    var_dump($syo);

echo sprintf("dは\t%d\n", $syo);
echo sprintf("fは\t%f\n", $syo);
echo sprintf(".1fは\t%.1f\n", $syo);
echo sprintf(".2fは\t%.2f\n", $syo);
echo sprintf("04dは\t%04d\n", $syo);
echo sprintf("Fは\t%F\n", $syo);

実行結果

-sh-4.1$ php sho.php
float(23.555)
dは     23
fは     23.555000
.1fは   23.6 ←これは繰り上がるのに
.2fは   23.55 ←これは繰り上がってない?
04dは   0023
Fは     23.555000
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした