Hàm number_format () PHP
Thí dụ
Định dạng số:
<?php
echo number_format("1000000")."<br>";
echo number_format("1000000",2)."<br>";
echo number_format("1000000",2,",",".");
?>
Định nghĩa và Cách sử dụng
Hàm number_format () định dạng một số với hàng nghìn được nhóm lại.
Lưu ý: Hàm này hỗ trợ một, hai hoặc bốn tham số (không phải ba).
Cú pháp
number_format(number,decimals,decimalpoint,separator)
Giá trị tham số
Parameter | Description |
---|---|
number | Required. The number to be formatted. If no other parameters are set, the number will be formatted without decimals and with comma (,) as the thousands separator. |
decimals | Optional. Specifies how many decimals. If this parameter is set, the number will be formatted with a dot (.) as decimal point |
decimalpoint | Optional. Specifies what string to use for decimal point |
separator | Optional. Specifies what string to use for thousands separator. Only the first character of separator is used. For example, "xxx" will give the same output as "x" Note: If this parameter is given, all other parameters are required as well |
Chi tiết kỹ thuật
Giá trị trả lại: | Trả về số được định dạng |
---|---|
Phiên bản PHP: | 4+ |
Changelog: | Kể từ PHP 5.4, hàm này hỗ trợ nhiều byte trong các tham số thập phân và dấu phân cách . Chỉ byte đầu tiên của mỗi dấu phân tách được sử dụng trong các phiên bản cũ hơn. |
Các ví dụ khác
Thí dụ
Bạn muốn trả về một giá: Một tham số sẽ làm tròn số (nó sẽ được định dạng không có số thập phân). Hai tham số sẽ cho kết quả bạn muốn:
<?php
$num = 1999.9;
$formattedNum = number_format($num)."<br>";
echo $formattedNum;
$formattedNum = number_format($num, 2);
echo $formattedNum;
?>
❮ Tham chiếu chuỗi PHP