目录

PHP money_format() 函数

❮ PHP 字符串参考

示例

国际 en_US 格式:

<?php
$number = 1234.56;
setlocale(LC_MONETARY,"en_US");
echo money_format("The price is %i", $number);
?>

上面代码的输出将是:

The price is USD 1,234.56


定义和用法

Money_format() 函数返回一个格式化为货币字符串的字符串。

此函数在主字符串中有百分号 (%) 的位置插入格式化数字。

笔记:Money_format() 函数不适用于 Windows 平台。

提示:该功能经常与设置语言环境()功能。

提示:要查看所有可用的语言代码,请访问我们的语言代码参考。


语法

money_format( string,number)

参数值

Parameter Description
string Required. Specifies the string to be formatted and how to format the variables in it.

Possible format values:

Padding and Flags:

  • =f - Specifies the character (f) to be used as padding (Example: %=t this uses "t" as padding). Default is space
  • ^ - Removes the use of grouping characters
  • + or ( - Specifies how to show positive and negative numbers. If "+" is used, the local setting for + and - will be used (usually a sign in front of negative numbers, and nothing in front of positive numbers). If "(" is used, negative numbers are enclosed in parenthesis. Default is "+"
  • ! - Stops the use of currency symbols in the output string
  • - If "-" is used, all fields are left-justified. Default is right-justified

Field width:

  • x - Specifies the minimum field width (x). Default is 0
  • #x - Specifies the maximum number (x) of digits expected to the left of the decimal point. This is used to keep formatted output aligned in the same columns. If the number of digits are bigger than x, this specification is ignored
  • .x - Specifies the maximum number (x) of digits expected to the right of the decimal point. If x is 0, the decimal point and the digits to its right will not be shown. Default is local settings

Conversion characters:

  • i - The number is formatted to international currency format
  • n - The number is formatted to national currency format
  • % - Returns the % character

Note: If multiple format values are used, they must be in the same order as shown above.

Note: This function is affected by local settings.

number Required. The number to be inserted at the %-sign in the format string


技术细节

返回值: 返回格式化的字符串。格式化字符串之前和之后的字符将原样返回。非数字导致返回 NULL 并发出 E_WARNING
PHP 版本: 4.3.0+

更多示例

示例

国际格式(德国),保留 2 位小数:

<?php
$number = 1234.56;
setlocale(LC_MONETARY,"de_DE");
echo money_format("%.2n", $number);
?>

上面代码的输出将是:

1 234,56 EUR

示例

负数,美国国家格式,用 () 表示负数,右精度 2 位数字,"*" 作为填充字符:

<?php
$number = -1234.5672;
echo money_format("%=*(#10.2n",$number);
?>

上面代码的输出将是:

(******1234.57)


❮ PHP 字符串参考