You are here

function format_number_significant_figures in Format Number API 7

Same name and namespace in other branches
  1. 6 format_number.module \format_number_significant_figures()

Formats numbers to a specified number of significant figures.

Parameters

number $number: The number to format.

integer $significant_figures: The number of significant figures to round and format the number to.

Return value

string The rounded and formatted number.

File

./format_number.module, line 212
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_significant_figures($number, $significant_figures) {

  // Compute the number of decimal places we need to round and format the
  // number to (may be negative).
  $decimals = floor($significant_figures - log10(abs($number)));

  // Round as a regular number.
  $number = round($number, $decimals);

  // We do not want decimals if the resulting number is zero.
  if ($number == 0) {
    $decimals = 0;
  }

  // Leave the formatting to format_number().
  return format_number($number, $decimals);
}