Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

JavaScript Calculator Bug!

Hey there, I am on a JavaScript calculator project, but I have run into an issue that I am struggling to resolve. I want my calculator to display at most 9 characters, including a ‘-’ and ‘.’, but my trouble is that whenever a minus or a dot is put into my string my function that cuts off the extra characters doesn’t work. Try pressing a button 9 times and you will see that it will cap itself and not overflow. Press the +/- button, or add a decimal in there and it will go on forever. switch it back to positive and it cuts off. I have spent a while on this and I haven’t had any luck. I appreciate the feedback and if you notice anywhere else my code can improve please let me know.

Give a search for this and you will see all the places I am trying to run the function: $('#total').html(checkLength(number));

https://codepen.io/tsjohns9/pen/rzOypK?editors=1111

Including your code will greatly increase the chances, we as a community, to help you.

Whoops, its in there now

1 Answer

Steven Parker
Steven Parker
243,657 Points

Function checkLength was checking the value of num itself instead of its length:

//Checks if number is longer than 9 
  function checkLength(num) {
    if (num.length > 9) {           // <- was originally "num > 9"
      return num.substr(0, 9);
    }
    return num;
  }

But it does seem a bit odd that converting a number to negative would also divide it by 10!

You are awesome

I have a question for you though Steven now that you fixed that problem. What is the best way to cleanly add decimal numbers because it doesn't seem to consistently add up the right way. And, my Math.abs method to switch between positive and negative rounds my decimals which I don't want either.

Steven Parker
Steven Parker
243,657 Points

It's not Math.abs but using parseInt to convert the string that truncates the decimals. Use parseFloat instead.

I'm not sure what you mean by "doesn't seem to consistently add up the right way" — can you give some specific examples?

Try adding two decimals together like .1 + .2 and you get .3000000. Or .78 - 3 and you get -2.219999

When does converting a number to negative divide it by 10? I haven't come across that.