For example, if the amount is 100.02, then the database needs to be saved as 10002.
Reply content:
For example, if the amount is 100.02, then the database needs to be saved as 10002.
Hope to help you:
- Code Puzzle (iv)-floating point (from surprise to thinking)
- Code Puzzle (v)-floating point number (who stole your accuracy?) )
Floating-point calculations are imprecise
Why do you use plastic surgery? Can't I use the decimal field type ? If calculations are involved, in order to maintain maximum accuracy, you can use the BC math function in PHP. Note that floating-point numbers should not be fully stored in the computer at this time, only to the fullest extent. Unless, you read from the database or get floating-point numbers from outside such as get parameters.
In the actual project, if the commodity price is involved in the subtraction operation, it will also be in accordance with some rules for trade-offs. Such as: rounding, upward increment, banker rounding, and so on.
Integers are accurate and fast ...
The floating-point number is inaccurate and the calculation is biased.
The precision of floating-point numbers:
http://php.net/manual/zh/language.types.float.php
A rational number that can be accurately represented in decimal, such as 0.1 or 0.7, cannot be accurately represented by the binary used internally, regardless of the number of mantissa.
Therefore, you cannot convert to a binary format without losing a little bit of precision.
This can result in confusion, such as floor (0.1+0.7) *10 typically returns 7 instead of the expected 8.
Because the internal representation of the result is actually similar to the 7.9999999999999991118 ...
Never believe that the floating-point number is accurate to the last, and never compare two floating-point numbers for equality.
If you do need higher precision, you should use the Bcmath (Binary Calculator Math) function or the GMP (GNU multiple Precision) function.
http://php.net/manual/zh/ref.bc.php
http://php.net/manual/zh/ref.gmp.php
For the sake of insurance, we should use strings to hold large integers and calculate them using a library of mathematical functions such as Bcmath.
For example, using PHP to calculate the balance of the account, you can use the Bcmath series arbitrary precision mathematical calculation function.
Add Bcadd
Minus Bcsub
by Bcmul
Except Bcdiv
Exponentiation Bcpow
Open square root bcsqrt
Compare Bccomp
Modulo (for remainder) bcmod
浮点数存在精度的问题,数据库字段采用float和double型都容易产生误差.
如果存储对精度要求比较高的数据,比如账户余额,就不能使用float型了,这时应该使用decimal型.
比如我们将MySQL数据库字段"账户余额"的数据类型定义为decimal(5,2),这样就可以存放-999.99到999.99范围内的数,并且不会出现误差.括号里左边的数表示总有效位数,右边的数表示小数位数.如果范围不够用,可以定义为decimal(10,2).