如何处理 Actionscript 中的数字精度? [英] How to deal with Number precision in Actionscript?

查看:25
本文介绍了如何处理 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 by 10; that gives us 1.2345678.
    • When we round 1.2345678, we get 1.0,
    • and finally, 1.0 divided by 10 equals 0.1.
    • 另一个例子:

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

      • 1.7302394309234435乘以10000;这给了我们 17302.394309234435.
      • 当我们舍入 17302.394309234435 时,我们得到 17302
      • 最后,17302 除以 10000 等于 1.7302.
        • Multiply 1.7302394309234435 by 10000; that gives us 17302.394309234435.
        • When we round 17302.394309234435 we get 17302,
        • and finally, 17302 divided by 10000 equals 1.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆