Using WordPress ‘number_format_i18n’ PHP filter

The number_format_i18n WordPress PHP filter formats a number based on the current locale.

Usage

add_filter('number_format_i18n', 'custom_number_format_i18n', 10, 3);
function custom_number_format_i18n($formatted, $number, $decimals) {
    // your custom code here
    return $formatted;
}

Parameters

  • $formatted (string) – The converted number in string format.
  • $number (float) – The number to convert based on the locale.
  • $decimals (int) – Precision of the number of decimal places.

More information

See WordPress Developer Resources: number_format_i18n

Examples

Custom decimal precision

Change the decimal precision to 4 decimal places.

add_filter('number_format_i18n', 'custom_decimal_precision', 10, 3);
function custom_decimal_precision($formatted, $number, $decimals) {
    $formatted = number_format_i18n($number, 4);
    return $formatted;
}

Always round up

Always round up the number regardless of the decimal value.

add_filter('number_format_i18n', 'always_round_up', 10, 3);
function always_round_up($formatted, $number, $decimals) {
    $rounded_number = ceil($number);
    $formatted = number_format_i18n($rounded_number, $decimals);
    return $formatted;
}

Format number as currency

Format the number as currency with a specific currency symbol.

add_filter('number_format_i18n', 'format_number_as_currency', 10, 3);
function format_number_as_currency($formatted, $number, $decimals) {
    $currency_symbol = '$';
    $formatted = $currency_symbol . number_format_i18n($number, $decimals);
    return $formatted;
}

Remove decimal part

Remove the decimal part of the number, showing only the integer part.

add_filter('number_format_i18n', 'remove_decimal_part', 10, 3);
function remove_decimal_part($formatted, $number, $decimals) {
    $formatted = number_format_i18n($number, 0);
    return $formatted;
}

Add a custom suffix

Add a custom suffix to the formatted number.

add_filter('number_format_i18n', 'add_custom_suffix', 10, 3);
function add_custom_suffix($formatted, $number, $decimals) {
    $suffix = ' points';
    $formatted = number_format_i18n($number, $decimals) . $suffix;
    return $formatted;
}