函数文档

number_format_i18n()

💡 云策文档标注

概述

number_format_i18n() 是一个 WordPress 函数,用于根据当前区域设置(locale)格式化浮点数。它基于 PHP 的 number_format() 函数,但自动应用本地化的千位分隔符和小数点符号。

关键要点

  • 函数签名:number_format_i18n( $number, $decimals = 0 ),其中 $number 为要格式化的浮点数(必需),$decimals 为小数位数(可选,默认 0)。
  • 返回值:格式化后的字符串,使用 $wp_locale 中的 number_format 设置(如 decimal_point 和 thousands_sep),若未设置则回退到默认格式。
  • 提供过滤器:apply_filters( 'number_format_i18n', $formatted, $number, $decimals ),允许开发者自定义格式化输出。
  • 相关函数:依赖 absint() 确保 $decimals 为非负整数,并常用于 WordPress 核心的多个场景,如显示评论数、分页链接等。

代码示例

$number = 3948;
$formatted = number_format_i18n( $number ); // 输出类似 "3,948"

$formatted = number_format_i18n( $number, 2 ); // 输出类似 "3,948.00"

📄 原文内容

Converts float number to format based on the locale.

Parameters

$numberfloatrequired
The number to convert based on locale.
$decimalsintoptional
Precision of the number of decimal places. Default 0.

Return

string Converted number in string format.

More Information

i18n is an abbreviation for internationalization.

Source

function number_format_i18n( $number, $decimals = 0 ) {
	global $wp_locale;

	if ( isset( $wp_locale ) ) {
		$formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
	} else {
		$formatted = number_format( $number, absint( $decimals ) );
	}

	/**
	 * Filters the number formatted based on the locale.
	 *
	 * @since 2.8.0
	 * @since 4.9.0 The `$number` and `$decimals` parameters were added.
	 *
	 * @param string $formatted Converted number in string format.
	 * @param float  $number    The number to convert based on locale.
	 * @param int    $decimals  Precision of the number of decimal places.
	 */
	return apply_filters( 'number_format_i18n', $formatted, $number, $decimals );
}

Hooks

apply_filters( ‘number_format_i18n’, string $formatted, float $number, int $decimals )

Filters the number formatted based on the locale.

Changelog

Version Description
2.3.0 Introduced.

User Contributed Notes