Simple math with decimals in PHP

后端 未结 4 1210
抹茶落季
抹茶落季 2021-01-22 05:11

This is killing me! I\'ve never had so much trouble and I can\'t figure out what I\'m doing wrong here.

If I have a number, say 2.32, and I want to do math with it it wo

4条回答
  •  萌比男神i
    2021-01-22 05:37

    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.

提交回复
热议问题