Home  >  Article  >  Backend Development  >  How to format a number with thousands separator in PHP

How to format a number with thousands separator in PHP

autoload
autoloadOriginal
2021-04-13 16:40:062546browse

How to format a number with thousands separator in PHP

## In the process of daily use of numbers, there are always some special scenarios where numbers need to be displayed in a specific form. This article mainly talks about how to use number_format () function to display numbers with thousands separators.

1.number_format () syntax

number_format( float $number , int $decimals = 0  , string $dec_point = "."  , string $thousands_sep = "," )

  • $number: the number to be formatted

  • $decimals: The number of decimal places to be retained

  • $dec_point: Specify the character displayed for the decimal point

  • $thousands_sep: Specify the thousands separator Displayed characters

Return value: number after formatting.

PS: Note

  • If only the first parameter is provided, the decimal part of the number will be removed, and it will be separated by English "," by default.

  • If two parameters are provided, number will retain the number of digits after the decimal point to the value of $decimals

  • If four parameters are provided, number will retain the decimal part of $decimals length, the decimal point is replaced by $dec_point, and the thousands separator is replaced by $thousands_sep.

2. Usage example:

There is only one parameter

<?php
    $number = 12399.563;
    //只有一个参数
    $number1 = number_format($number);
    echo "$number1"."<br>";
    // 12,400

There are two parameters


<?php
    $number2 =number_format($number,2);
    echo "$number2"."<br>";
    // 12,399.56
?>

There are four parameters


<?php
    $number = 12348.56789;
    $number3 = number_format($number, 2, &#39;,&#39;, &#39; &#39;);
    echo "$number3"."<br>";
    // 12 348,57
?>

Recommended: 2021 PHP interview questions summary (collection)》《php video tutorial

The above is the detailed content of How to format a number with thousands separator 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