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
Trevor Johnson
14,427 PointsJavaScript 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));
Trevor Johnson
14,427 PointsWhoops, its in there now
1 Answer
Steven Parker
243,657 PointsFunction 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!
Trevor Johnson
14,427 PointsYou are awesome
Trevor Johnson
14,427 PointsI 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
243,657 PointsIt'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?
Trevor Johnson
14,427 PointsTry adding two decimals together like .1 + .2 and you get .3000000. Or .78 - 3 and you get -2.219999
Trevor Johnson
14,427 PointsWhen does converting a number to negative divide it by 10? I haven't come across that.
Ivan Penchev
13,833 PointsIvan Penchev
13,833 PointsIncluding your code will greatly increase the chances, we as a community, to help you.