Developers/Price calculation and comparison

From Aimeos documentation

Developers
Other languages:
English 100% • ‎русский 86%


Price calculations and comparison

When calculating with numbers, PHP always uses floating point precision values to store the (intermediate) result and their precision is limited. Even if the rounding error is very small, sometimes it may have confusing effects especially if you compare the result with a decimal string value, e.g.

  1. ( $result == '0.7' ? true : false )

Depending on the calculations you've done before, the $result variable might have a slightly different value, e.g. 0.69999999. When comparing those values, the result will be "false" instead of the expected "true". As long as your comparison includes smaller (<=) or greater (>=) values as well, this won't be a problem, but if you exactly need to compare with a fixed value, then you must use this approach:

  1. abs( $result - '0.7' ) < 0.01

This compares if the difference between both values is smaller than the error we can't tolerate. Please also have a look at the page of the PHP floating point type to get more information about this topic.