How to deal with Number precision in Actionscript?

后端 未结 14 1233
自闭症患者
自闭症患者 2020-11-29 03:23

I have BigDecimal objects serialized with BlazeDS to Actionscript. Once they hit Actionscript as Number objects, they have values like:

140475.32 turns

14条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 04:07

    If you know the precision you need beforehand, you could store the numbers scaled so that the smallest amount you need is a whole value. For example, store the numbers as cents rather than dollars.

    If that's not an option, how about something like this:

    function printTwoDecimals(x)
    {
       printWithNoDecimals(x);
       print(".");
       var scaled = Math.round(x * 100);
       printWithNoDecimals(scaled % 100);
    }
    

    (With however you print with no decimals stuck in there.)

    This won't work for really big numbers, though, because you can still lose precision.

提交回复
热议问题