1
votes

I am creating a simple counter application for Flash (AS3) and have stripped it back to the bare minimum as I am encountering a very simple but core problem.

There are two buttons on the stage, one that adds 1.9 to a variable when pressed and one that subtracts 1.9 to the variable when pressed. There is then a dynamic text box that displays the value of the variable as a string.

The problem I am having is that once the counter gets to what shout be 5.7, it displays "5.69999999999" and this continues from then on from then with the occasional number being wrong. i.e. "15.200000000001" etc.

My code is below, I would appreciate if anyone can shed any light on what is going wrong.

var count:Number= 0;
counter.text = '0';

myBtn1.addEventListener(MouseEvent.CLICK, btnClick1);
myBtn2.addEventListener(MouseEvent.CLICK, btnClick2);

function btnClick1(event:MouseEvent):void
{
    addCount();
}

function btnClick2(event:MouseEvent):void
{

    takeCount();
}

function addCount():void
{
    count += 1.9;
    counter.text = count.toString();
}

function takeCount():void
{
    count -=1.9;
    counter.text = count.toString();
}
2

2 Answers

1
votes

I replicated your problem and cannot find the source of it. However you could use a simple rounding sytem to fix it such as

var count:Number= 0;
counter.text = "0";

myBtn1.addEventListener(MouseEvent.CLICK, btnClick1);
myBtn2.addEventListener(MouseEvent.CLICK, btnClick2);

function btnClick1(event:MouseEvent):void
{
addCount();
}

function btnClick2(event:MouseEvent):void
{

takeCount();
}

function addCount():void
{
count += 1.9;
count=roundDecimal(count, 1)
counter.text = count.toString();
}

function takeCount():void
{
count -=1.9;
count=roundDecimal(count, 1)
counter.text = count.toString();
}

function roundDecimal(num:Number, precision:int):Number{

var decimal:Number = Math.pow(10, precision);

return Math.round(decimal* num) / decimal;

}
1
votes

Instead of assigning the text to count.toString() you can use toFixed() function, that will return a fixed-decimal precision text. Give it a parameter of required decimal digits to output, and you're set, without any Math.pow() tricks.

counter.text=count.toFixed(1);

The Number.toFixed() manual