Home  >  Article  >  Backend Development  >  What are the methods to determine the exact number of decimal places in PHP?

What are the methods to determine the exact number of decimal places in PHP?

青灯夜游
青灯夜游Original
2021-09-14 18:21:122959browse

php Method for decimal precision: 1. Use sprintf() function to format, syntax "sprintf("%.decimal digits f",$num)"; 2. Use number_format() function , syntax "number_format($num,'number of decimal places')".

What are the methods to determine the exact number of decimal places in PHP?

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php decimal precision decimal point Method for the last digit

Method 1: Use sprintf to format the string

<?php
header("Content-type:text/html;charset=utf-8");
$num = 10.4567;
$format_num = sprintf("%.2f",$num);
echo $format_num;  //10.46
?>

What are the methods to determine the exact number of decimal places in PHP?

Method 2: Use the number_format() function

number_format(): The function can format numbers by grouping thousands.

Syntax:

number_format(number,decimals,decimalpoint,separator)

Parameters:

  • number: required. The number to format.

  • decimals: Optional. Specify how many decimal points

  • decimalpoint: Optional. Specifies the string used as the decimal point.

  • separator: Optional. Specifies the string used as thousands separator.

Example:

<?php
header("Content-type:text/html;charset=utf-8");
$num = 10.4567;
$format_num = number_format($num,&#39;1&#39;);
echo $format_num."<br>";
$format_num = number_format($num,&#39;2&#39;);
echo $format_num."<br>";
$format_num = number_format($num,&#39;3&#39;);
echo $format_num;
?>

What are the methods to determine the exact number of decimal places in PHP?

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of What are the methods to determine the exact number of decimal places 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