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

Tutorial example of how many decimal places to retain in PHP

零下一度
Release: 2023-03-10 18:26:02
Original
4537 people have browsed it

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>";
Copy after login

//2. Keep 2 decimal places, but not rounded

echo ((int)($n*100))/100;
Copy after login

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]] )
Copy after login

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?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template