本文介绍了对于大约1,2或3个小数的值,我应该使用BCMath吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中大约有10-15个数字,精度为1、2或3个小数,有符号和无符号.

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

使用的数据类型示例:

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

我正在用PHP计算它们,如下所示:

I'm calculating them in PHP something like this:

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

然后我正在使用某些round()函数,如下所示:

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

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

$result_round的结果最大为:100.000,999

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

我正在检查以下内容: bcmath PHP的精度是多少库?并回答说,如果您不使用round(),printf等函数,就不会有问题.

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.

那我应该使用BCMath扩展吗? (只是因为我正在使用round())

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

推荐答案

某些通用数字无法精确地用二进制表示(通用,我的意思是它们频繁出现在基于人的系统中,显然这本身就是胡说八道).例如0.1、0.2.要了解有关二进制fp的一些问题,请查看以下问题为什么十进制数字不能完全用二进制表示?

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?

对于许多常见应用程序,二进制浮点数是错误的选择.例如,金钱计算将是错误的",因为作为人类,我们期望以十进制数计数到预定的小数位数(对于货币则为2).在财务计算中使用二进制fp导致的舍入错误甚至可能是被盗的机会!

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实现了十进制FP,因此通常是一个更安全的选择.

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

例如在科学实验中测量真实值时,二进制FP很好.

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

如果您认为要存储固定数量的小数点,那么您可能确实想要bcmath而不是标准的二进制浮点数.另外,如果您使用的是bcmath,请检查您的数据库表示形式并在那里也使用十进制类型.

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.

这篇关于对于大约1,2或3个小数的值,我应该使用BCMath吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 17:30