Skip to content

Instantly share code, notes, and snippets.

@Glutexo
Created September 2, 2016 14:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Glutexo/431c67c27eefd4b258121d12b802f318 to your computer and use it in GitHub Desktop.
Save Glutexo/431c67c27eefd4b258121d12b802f318 to your computer and use it in GitHub Desktop.
Converts an exponential (scientific) number notation to a decimal one using neither GMP nor BCMath module.
<?php
/**
* Converts an exponential (scientific) number notation to a decimal one.
* Uses neither GMP nor BCMath modules.
*
* @param float|int|string $value
* @return string
*/
function formatExponential($value) {
// Both upper-case “E” and lower-case “e” would work.
$normalized = strtolower(trim($value));
$exponential = strpos($normalized, 'e');
if($exponential === false) {
if(strpos($normalized, '.') === false) {
$integerPart = $normalized;
$normalizedDecimalPart = '0';
} else {
list($integerPart, $decimalPart) = explode('.', $normalized);
$normalizedDecimalPart = rtrim($decimalPart, '0');
}
$normalizedIntegerPart = ltrim($integerPart, '0');
$formatted = $normalizedIntegerPart . '.' . $normalizedDecimalPart;
} else {
list($mantissa, $exponent) = explode('e', $normalized);
// Removing + sign not to break figure count.
$normalizedMantissa = ltrim($mantissa, '+');
if(strpos($normalizedMantissa, '.') === false) {
$mantissaIntegerPart = $normalizedMantissa;
$flatMantissa = $normalizedMantissa;
} else {
list($mantissaIntegerPart, $mantissaDecimalPart) = explode(
'.', $normalizedMantissa
);
$flatMantissa = $mantissaIntegerPart . $mantissaDecimalPart;
}
$flatMantissaLength = strlen($flatMantissa);
$mantissaIntegerPartLength = strlen($mantissaIntegerPart);
if($exponent >= 0) {
$targetLength = $exponent + $mantissaIntegerPartLength;
if($flatMantissaLength > $targetLength) {
$intergerPart = substr($flatMantissa, 0, $targetLength);
$decimalPart = substr($flatMantissa, $targetLength);
$formatted = $intergerPart . '.' . $decimalPart;
} else { // $flatMantissaLength <= $targetLength
$delta = $targetLength - $flatMantissaLength;
$formatted = $flatMantissa . str_repeat('0', $delta);
}
} else { // $exponent < 0
$targetZeroesLength =
abs($exponent) - $mantissaIntegerPartLength;
$zeroes = str_repeat('0', $targetZeroesLength);
$formatted = '0.' . $zeroes . $flatMantissa;
}
}
return $formatted;
}
@lexoring
Copy link

lexoring commented Nov 2, 2022

Hello. If you enter, for example, such a number -5.6258831787109375E-9, then it will not convert correctly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment