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

狂风中的少年 提交于 2019-12-07 07:20:55

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/23732640/should-i-use-bcmath-for-values-with-about-1-2-or-3-decimals

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!