0

I have PHP 7.4.27 with the following code: floatval($resultSet['p']) * intval($product->nr)

when $resultSet['p'] = 189.27 and $product->nr = 3, the result is 567.8100000000001

what's up with all those decimals? other float values and other integer values don't give me that kind of result

  • Use [bc math](https://www.php.net/manual/en/book.bc.php) functions. – vee Feb 10 '22 at 18:03
  • @vee: What would that solve? And why? – KIKO Software Feb 10 '22 at 18:06
  • @KIKOSoftware Maybe I confuse it with JS. For example **0.1+0.2** in JS is **0.30000000000000004**. This is weird result as in the question but as I try the OP's numbers the result is **567.81** correctly. Can't reproduce **567.8100000000001**. However bc math functions are good for high precision calculation. Example: `var_dump((0.1+0.2) == 0.3);` is `false` while `var_dump(bcadd(0.1, 0.2, 2) == 0.3);` is `true`. – vee Feb 11 '22 at 07:29
  • @vee Using [arbitrary-precision arithmetic](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic) does have its application, but is not as practical as [fixed-point arithmetic](https://en.wikipedia.org/wiki/Fixed-point_arithmetic). In the question the price of a product is multiplied by the quantity, hardly a situation with complex requirements. It can be done by using integers: 18927 * 3 = 56781. This is a common solution when using money. Alternatively there is [round()](https://www.php.net/manual/en/function.round). Floats can be used, when you take their properties into account. – KIKO Software Feb 11 '22 at 08:24
  • @KIKOSoftware Thank you. I have read those but still not understand. I'm stupid about this (I don't like math, numbers). I'm already read those few times ago but still...know nothing. :D... I hope those functions can be work because I see them in many many e-commerce software. – vee Feb 11 '22 at 12:26
  • @vee Normal [floats in PHP](https://www.php.net/manual/en/language.types.float.php) have a precision of roughly 16 digits. Given that money usually has two decimals your web shop would have to have an order worth more than say 9,999,999,999,999.99 before you get into trouble. Also notice all the zero's in 0.30000000000000004. That 4 is totally insignificant. If you want to check if that is equal to 0.3 you don't do `0.1 + 0.2 == 0.3`, but you do `math.abs((0.1 + 0.2) - 0.3) < 0.00001`. But clearly you have to know what you're doing and realize that these floats have a limited precision. – KIKO Software Feb 11 '22 at 12:41

0 Answers0