Skip to content

Instantly share code, notes, and snippets.

@dejurin
Created December 11, 2017 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dejurin/92de8ca929d26ea575ce9a3e481c6515 to your computer and use it in GitHub Desktop.
Save dejurin/92de8ca929d26ea575ce9a3e481c6515 to your computer and use it in GitHub Desktop.
PHP: [number_forma] floating with decimal, with safe zero
<?php
public function _number_format($number, $bs = '', $decimal = 0)
{
if (($e = strrchr($number, 'E')) === false) {
$len = strlen(substr(strstr($number, '.'), 1));
}
else {
$len = -intval(substr($e, 1));
}
$number = rtrim(sprintf('%.'.$len.'F', $number), '0');
$dec = 0;
if (strcmp($number + 0, (int) $number) != 0) {
$dec = 2;
preg_match("/\d+\.(0+|)\d\d/", $number, $m);
if ($m) {
$dec = strlen($m[1]) + $dec;
}
$dec = ($decimal > 0) ? $decimal : $dec;
}
$arr = explode(',', number_format($number, $dec, '.', $bs));
return (isset($arr[1])) ? rtrim($arr[0].','.rtrim($arr[1], '0'), ',') : $arr[0];
}
/* Print results
0.000000000012 -> 0.00000000001
1.123456789015 -> 1.12
1.000100000533 -> 1.00010
1.00000000000000533 -> 1.0000000000000053
1.000000000000000001 -> 1
1.00000000000000001 -> 1
1001.0000000000001 -> 1001.0000000000001
1001.00000000000000001 -> 1001
1.0000000000000000000000000000 -> 1
100056789.1235 -> 100056789.12
1 -> 1
1.0 -> 1
1.00 -> 1
0.001 -> 0.001
0.000000000001 -> 0.000000000001
*/
/*
php -v
PHP 7.1.12 (cli) (built: Dec 1 2017 13:53:12) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
*/
/*
php -i | grep precision
precision => 17 => 17
serialize_precision => -1 => -1
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment