php - Error With Using (int) and (double) together to Cut off Decimals -
php - Error With Using (int) and (double) together to Cut off Decimals -
when using (int) (double) times not working correct. @ php code example:
i need leave 2 decimals , remove other... i know number_format(); function cannot utilize it. because rounding number
number_format(24.299,2);
output: 24.30 need: 24.29
<?php $str="158.2"; echo (double)$str; // output: 158.2 echo (double)$str*100; // output: 15820 echo (int)((double)$str*100); // output: 15819 <-why? must 15820, why 15819? echo ((int)((double)$str*100)/100); // output: 158.19 ?>
i need leave 2 decimals in number , cutting other without rounding.
because of floating point precision (see illustration question: php math precision), 158.2 * 100
not exactly 15820
15819.99999999
.
now (int)
type conversion, not rounding, , digits after point cutting of.
i need leave 2 decimals in number , cutting other without rounding.
this easy:
number_format($str, 2);
update
number_format
does round, bit more complicated:
bcmul($str,100,0)/100
bcmul
multiplies arbitrary precision, in case 0. results:
bcmul(158.2,100,0)/100 == 158.2 bcmul(24.299,100,0)/100 == 24.29
php floating-point int double floating-point-precision
Comments
Post a Comment