Simple math with decimals in PHP

萝らか妹 提交于 2019-12-02 00:30:30

You need to assign $income in the following manner to get rid of the underlying SimpleXMLElement:

$income = (float) $commission;

Example of what happens when you don't:

$x = simplexml_load_string("<a>2.4</a>");
echo $x * 100; // output:  200

Besides using floats as Tim said, also make sure to use the BC Math functions when performing arithmetic operation on floating point numbers. Specifically bcmul():

$income100 = bcmul($income, 100);

The problem with floating-point numbers is that you cannot represent decimal numbers with them (unless it can be written as a/b for integer a and b, and even then only if abs(a) < pow(2,52) and b is a power of 2).

You may be better off using string functions to get an integer value:

$tmp = explode(".",$commission);
$tmp = intval($tmp[0].str_pad(substr($tmp[1],0,2),2,"0"));

This will split up the integer part from the decimal part, ensure the decima part is two digits long, and shove it on the end of the integer part, thus effectively multiplying the original number by 100.

I think the easiest solution would be to cast it to a float with floatval()

$income = floatval($comission)

leave the rest of the code as is and it should work as intended.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!