Last active
August 21, 2025 19:21
-
-
Save D1360-64RC14/d1d03f0bdff2daecbbcf4672b7cf33c3 to your computer and use it in GitHub Desktop.
Function to unwrap scientific notation into float number. Made with PHP 8.4.3.
This file contains hidden or 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 | |
function unwrapE(float $value) | |
{ | |
$strVal = strval($value); | |
if (!str_contains($strVal, 'E')) { | |
return $strVal; | |
} | |
[$beforeE, $afterE] = explode('E', $strVal); | |
[$beforeEBeforeDot, $beforeEAfterDot] = explode('.', $beforeE); | |
if ($beforeEAfterDot === '0') { | |
$beforeEAfterDot = ''; | |
} | |
$e = intval($afterE); | |
if ($e < 0) { | |
$resultZeroPadLen = strlen($beforeEAfterDot) + abs($e); | |
$result = str_pad($beforeEBeforeDot . $beforeEAfterDot, $resultZeroPadLen + 1, '0', STR_PAD_LEFT); | |
$result = substr_replace($result, '.', strlen($result) - $resultZeroPadLen, 0); | |
} else { | |
$resultZeroPadLen = $e; | |
$result = str_pad($beforeEAfterDot, $resultZeroPadLen, '0', STR_PAD_RIGHT); | |
$trailing = strlen($result) - $resultZeroPadLen; | |
if ($trailing < 0) { | |
$result = substr_replace($result, '.', $trailing, 0); | |
} | |
$result = $beforeEBeforeDot . $result; | |
} | |
return $result; | |
} | |
assert(unwrapE(1.25E-15) === '0.00000000000000125'); | |
assert(unwrapE(221.25E-15) === '0.00000000000022125'); | |
assert(unwrapE(0.25E-15) === '0.00000000000000025'); | |
assert(unwrapE(0.253E-15) === '0.000000000000000253'); | |
assert(unwrapE(123456789.25E-8) === '1.2345678925'); | |
assert(unwrapE(1E-30) === '0.000000000000000000000000000001'); | |
assert(unwrapE(0.1E-30) === '0.0000000000000000000000000000001'); | |
assert(unwrapE(0.5E30) === '500000000000000000000000000000'); | |
assert(unwrapE(0.5E+31) === '5000000000000000000000000000000'); | |
assert(unwrapE(5.1E+30) === '5100000000000000000000000000000'); | |
assert(unwrapE(2.5123456789123E+17) === '251234567891230000'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment