LoginSignup
36
38

More than 5 years have passed since last update.

数字のフォーマット(小数点含む!)

Last updated at Posted at 2012-12-26

number_formatにただぶっ込むと、勝手に小数点以下が四捨五入されて整数で返ってくるんですね。(お客さんに怒られました。)

hoge.php
<?php
echo number_format(1234.567); // 1,235
?>

小数点以下も含むには、第二引数に小数点以下の桁数を書くそうです。

hoge.php
<?php
echo number_format(1234.567,2); // 1,234.57
?>

これならいいですね。

しかし。
こう言う場合はどうでしょう?

hoge.php
<?php
echo number_format(1200.5,2); // 1,200.50
?>

気持ち悪いですね…

小数点以下の末尾の0は取っ払いましょう。

hoge.php
<?php
$number = number_format(1200.5,2); // 1,200.50
$number = preg_replace("/\.?0+$/","",$number); // 1,200.5
?>

これですっきりですね!

PHP: number_format - Manual - http://php.net/manual/ja/function.number-format.php

string number_format ( float $number [, int $decimals = 0 ] )
string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )
この関数は 1 つか 2 つもしくは 4 つのパラメータを受け取ります (3 つはありません) :
パラメータが 1 つだけ渡された場合、 number は千位毎にカンマ (",") が追加され、 小数なしでフォーマットされます。
パラメータが 2 つ渡された場合、number は decimals 桁の小数の前にドット (".") 、 千位毎にカンマ (",") が追加されてフォーマットされます。
パラメータが 4 つ全て渡された場合、number はドット (".") の代わりに dec_point が decimals 桁の小数の前に、千位毎にカンマ (",") の代わりに thousands_sep が追加されてフォーマットされます。

36
38
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
36
38