number_format

(PHP 4, PHP 5, PHP 7, PHP 8)

number_format以千位分隔符方式格式化一個(gè)數(shù)字

說(shuō)明

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

本函數(shù)可以接受1個(gè)、2個(gè)或者4個(gè)參數(shù)(注意:不能是3個(gè)):

如果只提供第一個(gè)參數(shù),number的小數(shù)部分會(huì)被去掉 并且每個(gè)千位分隔符都是英文小寫逗號(hào)","

如果提供兩個(gè)參數(shù),number將保留小數(shù)點(diǎn)后的位數(shù)到你設(shè)定的值,其余同樓上

如果提供了四個(gè)參數(shù),number 將保留decimals個(gè)長(zhǎng)度的小數(shù)部分, 小數(shù)點(diǎn)被替換為dec_point,千位分隔符替換為thousands_sep

參數(shù)

number

你要格式化的數(shù)字

decimals

要保留的小數(shù)位數(shù)

dec_point

指定小數(shù)點(diǎn)顯示的字符

thousands_sep

指定千位分隔符顯示的字符

返回值

格式化以后的 number.

更新日志

版本 說(shuō)明
5.4.0 This function now supports multiple bytes in dec_point and thousands_sep. Only the first byte of each separator was used in older versions.

范例

示例 #1 number_format() Example

For instance, French notation usually use two decimals, comma (',') as decimal separator, and space (' ') as thousand separator. The following example demonstrates various way to format a number:

<?php

$number 
1234.56;

// english notation (default)
$english_format_number number_format($number);
// 1,235

// French notation
$nombre_format_francais number_format($number2','' ');
// 1 234,56

$number 1234.5678;

// english notation without thousands separator
$english_format_number number_format($number2'.''');
// 1234.57

?>

更新日志

版本 說(shuō)明
7.2.0 number_format() 現(xiàn)在無(wú)法返回 -0,之前可能返回 -0,因?yàn)?number 可能會(huì)是 -0.01

參見