Should I use BCMath for values with about 1,2 or 3 decimals?
Asked Answered
P

1

7

I have about 10-15 numbers with precision of 1, 2 or 3 decimals in my db, both signed and unsigned.

Example of datatypes being used:

decimal(10,3), decimal(10,2), decimal(10,1)

I'm calculating them in PHP something like this:

$result = ($value1from_col1 + ($value2from_col2 * 30)/500) * 0.453;

I'm then using some round() functions like this:

$result_round = round($result, 2, PHP_ROUND_HALF_UP);

Result of $result_round would be at largest: 100.000,999

I'm checking this: How much precision for a bcmath PHP library? and the answer states that it wouldn't be an issue if you're not using functions like round(), printf etc.

Should I use BCMath-extension then? (just because I'm using round())

Presber answered 19/5, 2014 at 8:5 Comment(3)
How big are your integers?Halflight
@Halflight - just updated question.Presber
@Cagy79 the answer you reference is about whole numbers, no fractions, so does not apply hereSodamide
S
10

Some common numbers cannot be represented exactly in binary (by common, i mean they occur frequently in human based systems, obviously on its own that's a nonsense concept). For example, 0.1, 0.2. To understand some of the issues around binary fp have a look at this question Why can't decimal numbers be represented exactly in binary?

For many common applications, binary floating point is the wrong choice. For example, money calculations will be 'wrong' because as humans we expect to be counting in decimal, to a predetermined number of decimal places (2 in the case of money). Rounding errors caused by using binary fp in financial calculations can even be an opportunity for theft!

bcmath implements decimal FP and so is generally a safer choice.

For measurement of real world values eg in a science experiment then binary FP is fine.

If you think you are storing a fixed number of decimal points then you probably do want bcmath and not standard binary floating point. Also check your database representation and use a decimal type there too if you are using bcmath.

Sodamide answered 19/5, 2014 at 8:41 Comment(2)
So if I understand the link you've supplied correctly, the issue is mainly when you want divide (some) different numbers (with accurate precision)?Presber
Even addition can go wrong, e.g. if you add enough 0.1's together, and they are all out due to that number being un-representable in binary fp, then eventually you will be out by more than 0.01, for example.Sodamide

© 2022 - 2024 — McMap. All rights reserved.