问题
I have a problem with the following statement
trace(10.12+13.75) //output 23.869999999999997
Can anybody explain me why is this so and how to get exact 23.87 out of this?
Thanks
回答1:
That happens because of the precision of IEEE format.
Simplest would be to use toFixed.
var num:Number = 10.12+13.75;
var numStr:String = num.toFixed(2);
var num2:Number = new Number(numStr);
回答2:
Computer floating point numbers are not perfectly accurate. JavaScript (and I assume ActionScript, as it's a variant) uses 64-bit IEEE 754 values (ECMAScript spec ref). The best example of this imprecision is probably 0.1 + 0.2
, which comes out to 0.30000000000000004
. To get 23.87
, you'll have to round.
If you're doing financial math, you may (or may not) be better off using a library that does decimal math rather than IEEE floating point (something akin to Java's BigDecimal
class or C#'s decimal
type). But note that decimal types have their own limitations, such as not being able to represent 1 / 3
accurately.
来源:https://stackoverflow.com/questions/9015755/adding-2-decimal-number-gives-wrong-result-in-action-script