Created
September 2, 2016 14:15
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello. If you enter, for example, such a number -5.6258831787109375E-9, then it will not convert correctly.