Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lost data when convert float to int in php

Tags:

php

int

My code :

$baseprice=1705000/1.1;
var_dump($baseprice);
$parseprice=intval($baseprice);
var_dump($parseprice);

Result :

float(1550000) int(1549999)

As you can see, i lost 1 number when convert from float to int, where is it,what solution for this case for convert without lost data, Thanks.

like image 789
Mr.Lak Avatar asked Jul 26 '26 17:07

Mr.Lak


1 Answers

You are using floating point numbers which will lose precision (see this link).

If you are handling currency use integers and work in cents, pence, pfennigs, or whatever. Convert to a currency format just before display.