protected function GeneralNumberFormatter::numberFormatScientific in Formatter Suite 8
Formats a number using scientific notation.
Scientific notation formats a number with three parts:
- Whole part before the decimal.
- Fractional part after the decimal.
- Exponent for a power of 10.
Scientific notation follows international standards, so it is not subject to regional choices for a decimal separator and it does not support different positive and negative presentation styles.
The following formatting attributes are used:
- Exponent style.
- Decimal digits.
Parameters
mixed $number: The number to format.
Return value
string The formatted number, including the prefix or suffix.
1 call to GeneralNumberFormatter::numberFormatScientific()
- GeneralNumberFormatter::numberFormat in src/
Plugin/ Field/ FieldFormatter/ GeneralNumberFormatter.php - Format a number using the current settings.
File
- src/
Plugin/ Field/ FieldFormatter/ GeneralNumberFormatter.php, line 1363
Class
- GeneralNumberFormatter
- Format a number field with a variety of notation styles and parameters.
Namespace
Drupal\formatter_suite\Plugin\Field\FieldFormatterCode
protected function numberFormatScientific($number) {
// Get settings.
$usePrefixAndSuffix = $this
->getSetting('usePrefixAndSuffix');
$exponentStyle = $this
->getSetting('exponentStyle');
$decimalDigits = $this
->getSetting('decimalDigits');
// Use sprintf() to do an initial format into E-notation (the only
// one sprintf() supports). sprintf() will handle scaling up/down the
// number to a whole part with one digit, then calculating the
// exponent.
$fmt = '%' . ($decimalDigits + 2) . '.' . $decimalDigits . 'E';
$formatted = sprintf($fmt, (double) $number);
// Format the exponent.
switch ($exponentStyle) {
default:
case 'enotation':
// Use sprintf() output as-is since it produces E-notation.
break;
case 'superscript':
// Split the formatted output at the 'E' into mantissa and exponent.
// If this doesn't yield two parts, then the number was too small
// and simple to have an exponent (e.g. "1.0"). Just use the
// number as-is.
$parts = explode('E', $formatted);
if (count($parts) === 2) {
$formattedMantissa = $parts[0];
$formattedExponent = $parts[1];
// Format the exponent using an HTML <sup> tag.
$formatted = $formattedMantissa . 'x10<sup>' . $formattedExponent . '</sup>';
}
break;
}
// If needed, add the prefix and suffix.
if ($usePrefixAndSuffix === FALSE) {
return $formatted;
}
$prefixes = $this
->getFieldPrefixes();
$suffixes = $this
->getFieldSuffixes();
$prefix = $this
->selectPrefix($number, $prefixes);
$suffix = $this
->selectSuffix($number, $suffixes);
return $prefix . $formatted . $suffix;
}