Skip to main content
Inspiring
April 8, 2013
Answered

Can't figure out how to solve the decimal point bug in this calculator code

  • April 8, 2013
  • 1 reply
  • 1779 views

Hi guys, I'm new in flash and is currently learning how to build a simple calculator with multipliers (plus,minus,multiple,divide,decimal point and change sign) but I'm stuck on the decimal point and change sign.

var multiplier_old:Number = 10;

var multiplier_new:Number = 1;

// .: Sets the multipliers so that new input numbers become decimals of a lower unit column

action_point.addEventListener(MouseEvent.MOUSE_DOWN, function():void {

 

          multiplier_old = 1;

          multiplier_new = 0.1;

          point = true;

 

});

// Takes intput from the input_ buttons and adds it to the input after applying the multipliers.

// If `point` is true then the multiplier_new is divided by 10, also as described.

function inputNumber(n:Number):void {

 

          input = input * multiplier_old + n * multiplier_new;

 

                    if (point) {

                                    multiplier_new *= 0.1;

                   trace(multiplier_new);

                    }

 

          output_txt.text = input.toString();

}

Decimal point

The problem is that when I input 2.7 in the calculator, it will display the values in output_txt correctly. But then when I input 2.78, it will display 2.780000000000000000000000002. This will also happen to other numbers if the input is too big.

What I want is just 2.78. How do I change the codings to make 2.780000000000000000000000002 become 2.78?

Change sign

Any tips on how to start on this one?

Thanks for your time,

Zainu

This topic has been closed for replies.
Correct answer Ned Murphy

You need to use rounding in order to keep the numbers down to limited decimal values.  To display specific decimal values use the toFixed() method of the String class when writing the text to the textfield.

To change the sign, multiply by -1.

1 reply

Ned Murphy
Ned MurphyCorrect answer
Legend
April 8, 2013

You need to use rounding in order to keep the numbers down to limited decimal values.  To display specific decimal values use the toFixed() method of the String class when writing the text to the textfield.

To change the sign, multiply by -1.

ZainuuAuthor
Inspiring
April 8, 2013

Hi Ned Murphy,

Thanks for replying. How do I know what number is require to put in input.toFixed(?) because there can be many different amount of digits involve in the output depending what numbers the guy press in the caculator number buttons.

Ned Murphy
Legend
April 8, 2013

A calculator can allow you to specify how many decimal places to display, so what value you want in that argument is up to you to decide.  You can make it a user option or you can set it to a specific limit.