note 89475 modified in function.floatval by thiago
| From: | thiago@php.net | Date: | Tue, 10 Mar 2009 05:12:43 +0000 |
| Subject: | note 89475 modified in function.floatval by thiago | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-151674@lists.php.net to get a copy of this message | ||
i noticed all (well, unless i missed something) the functions working with decimals destroy trailing
decimal places. this function restores them in case you want to be able to display a consistent
precision for users.
<?php
function decimal($val, $precision = 0) {
if ((float) $val) :
$val = round((float) $val, (int) $precision);
list($a, $b) = explode('.', $val);
if (strlen($b) < $precision) $b = str_pad($b, $precision, '0', STR_PAD_RIGHT);
return $precision ? "$a.$b" : $a;
else : // do whatever you want with values that do not have a float
return $val;
endif;
}
?>
--was--
i noticed all (well, unless i missed something) the functions working with decimals destroy trailing
decimal places. this function restores them in case you want to be able to display a consistent
precision for users.
function decimal($val, $precision = 0) {
if ((float) $val) :
$val = round((float) $val, (int) $precision);
list($a, $b) = explode('.', $val);
if (strlen($b) < $precision) $b = str_pad($b, $precision, '0', STR_PAD_RIGHT);
return $precision ? "$a.$b" : $a;
else : // do whatever you want with values that do not have a float
return $val;
endif;
}
http://php.net/manual/en/function.floatval.php