如何处理 Actionscript 中的数字精度? [英] How to deal with Number precision in Actionscript?
问题描述
我已使用 BlazeDS 将 BigDecimal 对象序列化为 Actionscript.一旦它们将 Actionscript 作为 Number 对象命中,它们就会具有如下值:
I have BigDecimal objects serialized with BlazeDS to Actionscript. Once they hit Actionscript as Number objects, they have values like:
140475.32
变成 140475.31999999999998
我该如何处理?问题是,如果我使用 NumberFormatter 的精度为 2,则该值将被截断为 140475.31
.有什么想法吗?
How do I deal with this? The problem is that if I use a NumberFormatter with precision of 2, then the value is truncated to 140475.31
. Any ideas?
推荐答案
这是我针对该问题的通用解决方案(我有 在此处写了博客):
This is my generic solution for the problem (I have blogged about this here):
var toFixed:Function = function(number:Number, factor:int) {
return Math.round(number * factor)/factor;
}
例如:
trace(toFixed(0.12345678, 10)); //0.1
- 将
0.12345678
乘以10
;这给了我们1.2345678
. - 当我们取整
1.2345678
时,我们得到1.0
, - 最后,
1.0
除以10
等于0.1
. - Multiply
0.12345678
by10
; that gives us1.2345678
. - When we round
1.2345678
, we get1.0
, - and finally,
1.0
divided by10
equals0.1
.
另一个例子:
trace(toFixed(1.7302394309234435, 10000)); //1.7302
- 将
1.7302394309234435
乘以10000
;这给了我们17302.394309234435
. - 当我们舍入
17302.394309234435
时,我们得到17302
, - 最后,
17302
除以10000
等于1.7302
. - Multiply
1.7302394309234435
by10000
; that gives us17302.394309234435
. - When we round
17302.394309234435
we get17302
, - and finally,
17302
divided by10000
equals1.7302
.
<小时>编辑
基于匿名答案下面,对方法上的参数进行了很好的简化,使精度大大提高更直观.例如:
Based on the anonymous answer below, there is a nice simplification for the parameter on the method that makes the precision much more intuitive. e.g:
var setPrecision:Function = function(number:Number, precision:int) {
precision = Math.pow(10, precision);
return Math.round(number * precision)/precision;
}
var number:Number = 10.98813311;
trace(setPrecision(number,1)); //Result is 10.9
trace(setPrecision(number,2)); //Result is 10.98
trace(setPrecision(number,3)); //Result is 10.988 and so on
注意我在此处添加了此内容,以防万一有人将其视为答案并且不向下滚动...
N.B. I added this here just in case anyone sees this as the answer and doesn't scroll down...
这篇关于如何处理 Actionscript 中的数字精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!