Home  >  Article  >  Backend Development  >  Tutorial example of how many decimal places to retain in PHP

Tutorial example of how many decimal places to retain in PHP

零下一度
零下一度Original
2017-06-17 16:32:354503browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn