Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

bcmath

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())

like image 713
bestprogrammerintheworld Avatar asked May 19 '14 08:05

bestprogrammerintheworld


1 Answers

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.

like image 50
George Lund Avatar answered Oct 12 '22 22:10

George Lund