0

Possible Duplicate:
Is JavaScript's Math broken?
Round Number problem flex

I am having a problem with flex 4.5. I want to multiply 15.2*6, but instead of getting 91.2, I am getting 91.1999999999999. Here is my code, it is very simple and I have tried all variations. Thanks for any help. However, since I am working with a billing process, I don't want to use formatters. I shouldn't need to, I mean it's a very simple operation.

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
           xmlns:s="library://ns.adobe.com/flex/spark" 
           xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955"   minHeight="600">
<fx:Script>
    <![CDATA[
        public var precio:Number = new Number();
        public var cantidad:Number=new Number();
        public var resultado:Number=new Number();
        [Bindable]
        public var numeroToString:String=new String();
        public var numeroToString2:String=new String();
        //public var numerox:num


        protected function button1_clickHandler(event:MouseEvent):void
        {
            precio=parseFloat(precioTxt.text);
            cantidad=parseInt(cantidadTxt.text);
            resultado=precio*cantidad;
            resLabel.text=resultado.toString();

        }

    ]]>
</fx:Script>
<fx:Declarations>
<mx:NumberFormatter id="formateo"
                    rounding="up"
                    precision="3"
                    />  <!-- Place non-visual       elements (e.g., services, value objects) here -->
</fx:Declarations>

<s:TextInput id="cantidadTxt" x="136" y="77" prompt="introduce cantidad"/>
<s:TextInput id="precioTxt" x="136" y="107" prompt="introduce precio"/>
<s:Button x="176" y="155" label="calcular" click="button1_clickHandler(event)"/>
<s:Label id="resLabel" x="304" y="77" fontSize="20"/>
</s:Application>
Community
  • 1
  • 1

1 Answers1

2

The problem stems from the fact that floating point numbers can only represent a subset of all real numbers. So, in other words, with floating point arithmetics the result is the value closest to the correct result representable with floats.

If you are working with any system related to money, never use floating point numbers. Any rounding errors will easily accumulate in multi-step calculations which is very bad when dealing with money. You should use integers only, then these rounding problems will not happen - at least not with multiplication.

I believe that using the "." in ActionScript makes Number a floating point number. Use either int or be careful to keep Number as integer.

jhonkola
  • 3,385
  • 1
  • 17
  • 32