LoginSignup
17
20

More than 5 years have passed since last update.

【PHP】小数点以下まで出力する

Posted at

sprintfとprintfとnumber_formatがある。
いずれも指定した小数点以下で四捨五入して出力する。

sprintfとprintfの違いは、sprintfはフォーマットされた値が戻り値。printfはフォーマットされた値を標準出力する。
画面に表示する場合はどちらを使っても同じ。変数に入れたい場合は、sprintfを使うと良い。

$num1 = 10;
$num2 = 1000.5;
$num3 = 0.456789;

echo sprintf('%.2f',$num1),PHP_EOL;
echo sprintf('%.2f',$num2),PHP_EOL;
echo sprintf('%.2f',$num3),PHP_EOL;
/*
10.00
1000.50
0.46
*/

printf('%.2f',$num1);echo PHP_EOL;
printf('%.2f',$num2);echo PHP_EOL;
printf('%.2f',$num3);echo PHP_EOL;
/*
10.00
1000.50
0.46
*/

echo number_format($num1,2),PHP_EOL;
echo number_format($num2,2),PHP_EOL;
echo number_format($num3,2),PHP_EOL;
/*
10.00
1,000.50
0.46
*/

number_formatは千ごとにカンマが入るので、オプションでカンマなしにすることもできる。

//number_format(値,小数点何位まで,小数点の表示形式,千区切りの表示形式);
echo number_format($num1,2,null,'');
17
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
20