Created
October 11, 2018 13:11
-
-
Save ausi/3b244e836ac680a6c3f4b3bb1f82f85d to your computer and use it in GitHub Desktop.
Convert number/integer/float into string without exponential notation
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 | |
declare(strict_types=1); | |
function numberToString($number, $precision = null) | |
{ | |
if (is_int($number)) { | |
return (string) $number; | |
} | |
if ($precision === null) { | |
$precision = (int) ini_get('precision'); | |
} | |
$sign = ''; | |
$number = sprintf('%.' . ($precision - 1) . 'e', (float) $number); | |
if ($number[0] === '-') { | |
$sign = '-'; | |
$number = substr($number, 1); | |
} | |
if ($number[1] !== '.') { | |
throw new InvalidArgumentException( | |
sprintf('Unable to convert "%s" into a string representation.', $number) | |
); | |
} | |
$number = explode('e', $number); | |
$digits = rtrim($number[0][0] . substr($number[0], 2), '0'); | |
$shift = (int) $number[1] + 1; | |
if ($shift < 1) { | |
$result = '0.'.str_repeat('0', ($shift) * -1).$digits; | |
} | |
elseif (strlen($digits) <= $shift) { | |
$result = str_pad($digits, $shift, '0'); | |
} | |
else { | |
$result = substr($digits, 0, $shift).'.'.substr($digits, $shift); | |
} | |
return $sign.$result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
alternative: