Summary:

This Smarty modifier is essentially a wrapper around the php function [number_format]. However, unlike number_format, it takes special care of floating point numbers by preserving the existing fractional component (e.g. 123.456).

Thanks to Mike Saywell for pointing out a bug in the original code. This was fixed 9/15/2010. If you downloaded a version prior to that, please update to the code below.

Usage:

  |commify[:decimal_digits[:decimal_char[:thousands_char]]]

  decimal_digits is the number of digits to include after the decimal.  Setting this to -1 (the default) means preserve all digits.
  decimal_char is the seperator between the integer and fractional components (default: ".")
  thousands_char is the seperator between each group of three digits in the integer component (default: ",")

Example:

// php file

  $smarty->assign( 'number', '12345.678' );

// template

  Number format: {$number|number_format}
  Commify: {$number|commify}
  Fixed: {$number|commify:2}
  European: {$number|commify:-1:',':'.'}

// output

  Number format: 12,345
  Commify: 12,345.678
  Fixed: 12,345.68
  European: 12.345,678

Source:

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * Type:        modifier
 *
 * Name:        commify
 *
 * Purpose:     format numbers by inserting thousands seperators
 *              this is basically a wrapper for number_format
 *              with additional processing to retain the original
 *              digits after the decimal point (if any)
 *
 * Input:       string: number to be formatted
 *              decimals: [optional] number of decimal places
 *              dec_point: [optional] decimal point character
 *              thousands_sep: [optional] thousands seperator
 *
 * Examples:    {$number|commify}    12345.288 => 12,345.288
 *              {$number|commify:2}    12345.288 => 12,345.29
 *
 * Install:     Drop into the plugin directory as modifier.commify.php.
 *
 * Author:      James Brown <james [at] hmpg [dot] net>
 * -------------------------------------------------------------
 */
 
function smarty_modifier_commify($string, $decimals=-1, $dec_point='.', $thousands_sep=',')
{
    if ($decimals == -1)
    {
        if (preg_match('/(.*)\.(\d+.*)/', $string, $matches))
            return number_format($matches[1], 0, $dec_point, $thousands_sep) . $dec_point . $matches[2];
        else
            return number_format($string);
    }
    else
        return number_format($string, $decimals, $dec_point, $thousands_sep);
}
?>