function format_number in Format Number API 7
Same name and namespace in other branches
- 6 format_number.module \format_number()
Format a number with (site default or user defined) thousands separator and decimal point.
Parameters
float $number: The number being formatted.
int $decimals: Number of decimal digits. Use -1 for any number if decimals.
Return value
string The formatted number.
2 calls to format_number()
- format_number_numericfield_process in ./
format_number.module - Process an individual numeric form element.
- format_number_significant_figures in ./
format_number.module - Formats numbers to a specified number of significant figures.
3 string references to 'format_number'
- format_number_add_js in ./
format_number.module - Expose a javascript version of the Format Number API.
- format_number_form_user_profile_form_alter in ./
format_number.module - Implements hook_form_user_profile_form_alter().
- format_number_variable_info in ./
format_number.variable.inc - Implements hook_variable_info().
File
- ./
format_number.module, line 178 - This module provides a method to configure number formats (site default and user defined) with configurable decimal point and thousand separators. It also exposes several functions that can be used by other contributed or custom modules to display…
Code
function format_number($number, $decimals = 0) {
static $format_options;
if (!isset($format_options)) {
$format_options = format_number_get_options();
}
// Perform an initial conversion using PHP's number_format() that
// seems to work better than sprintf().
$number = number_format((double) $number, FORMAT_NUMBER_MAX_PRECISION, '.', '');
if ($decimals < 0) {
// Count decimal places (ignoring trailing zeros to the right of the decimal point).
$decimals = strpos($number, '.') === FALSE ? 0 : drupal_strlen(preg_replace('#^.*\\.([0-9]*?)0*$#', '\\1', $number));
}
// Avoid issues caused by PHP rounding limitations.
if ($decimals > FORMAT_NUMBER_MAX_PRECISION) {
$decimals = FORMAT_NUMBER_MAX_PRECISION;
}
// number_format() can only deal with one chararcter symbols, so that
// we tell him to use the placeholders X and Z that we replace later.
return str_replace(array(
'X',
'Z',
), array(
$format_options['decimal_point'],
$format_options['thousands_sep'],
), number_format($number, $decimals, 'X', 'Z'));
}