Home > Article > Backend Development > Tutorial example of how many decimal places to retain in PHP
Content of this section:
PHP retains several decimal places
Example:
<?php $n = "10.6789"; //一、保留2位小数点,并四舍五入 //使用round()方法 echo round($n,2); echo "<br>"; //使用number_format()方法 echo number_format($n,2);echo "<br>"; //使用sprintf()方法 echo sprintf("%.2f",$n);echo "<br>";
//2. Keep 2 decimal places, but not rounded
echo ((int)($n*100))/100;
Attached, PHP's function to get the number of decimal places number_format is a simple example.
string number_format ( float number [, int decimals [, string dec_point, string thousands_sep]] )
Code:
<? $short_pi = "3.14159";$my_pi = number_format($short_pi, 2);echo $my_pi."\n"; // 3.14$foo = 850017.9021; // www.jbxue.com$new_foo = number_format($foo, 3, ".", " ");echo $new_foo."\n"; // 850 017.902?>
Description:
number_format function is used to format the number $number.
The second function decimals is used to retain the following digits of the number.
The above is the detailed content of Tutorial example of how many decimal places to retain in PHP. For more information, please follow other related articles on the PHP Chinese website!