如何处理数precision在Actionscript中?如何处理、precision、Actionscript

2023-09-08 10:58:03 作者:你眉眼有我

我有BigDecimal与BlazeDS的以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

140475.32 turns into 140475.31999999999998

我该如何面对呢?问题是,如果我用用2 precision一个NumberFormatter类,则该值将被截​​断为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.

var toFixed:Function = function(number:Number, factor:int) {
  return Math.round(number * factor)/factor;
}

例如:

trace(toFixed(0.12345678, 10)); //0.1

乘以10 0.12345678。

Multiply 0.12345678 by 10.

这为我们提供了1.2345678。

That gives us 1.2345678.

当我们圆1.2345678得到1.0和1.0

When we round 1.2345678 we get 1.0 and 1.0

除以10等于0.1。

trace(toFixed(1.7302394309234435, 10000)); //1.7302

10000乘以1.7302394309234435。

Multiply 1.7302394309234435 by 10000.

这给了我们17302.394309234435。

That gives us 17302.394309234435.

当我们圆17302.394309234435我们得到17302和17302 10000分等于1.7302

When we round 17302.394309234435 we get 17302 and 17302 divided by 10000 equals 1.7302

修改

有一个很好的简化上,使precision更加直观方法的参数。例如,

Based on the anonymous answer below - http://stackoverflow.com/a/1541929/74861 - 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。我说这这里,以防万一有人认为这是答案,不向下滚动......

N.B. I added this here just in case anyone sees this as the answer and doesn't scroll down...

 
精彩推荐
图片推荐