Learning another language is never going to be a quick process. After all, it probably takes us a good 12 months before we can throw together even a basic babble of English…albeit this does get much quicker when learning a second language; español por ejemplo (thanks Duo!)
It was all going well, with the following produced thus far:
console.log('I\'m going to calculate your bill');
var billAmount = 100;
var tipPercentage = 0.2;
var tipAmount = billAmount * tipPercentage;
var totalBill = billAmount + tipAmount;
var tipAmount = tipAmount.toFixed(2);
var totalBill = totalBill.toFixed(2);
console.log('Your bill came to £' + billAmount);
console.log('You must leave a ' + tipPercentage*100 + '\% tip!');
console.log('You\'re leaving a £' + tipAmount + ' tip.');
console.log('Your total bill, including tip, came to £' + totalBill);
Note the ‘toFixed()’, for bonus points…! But then I wanted to improve it; I wanted to add a bit more functionality.
After a quick Google, I came across the ‘prompt()’ function, and proceeded to add a touch more functionality and user interaction:
var billAmount = prompt('How much was your bill?');
Unfortunately however, it was not as simple as this and all of a sudden the rest of the script seemed to stop working…
After re-reading what I had found for ‘prompt()’ on W3 Schools, and running the ‘Analyze JS’ option within CodePen to no errors, I was stumped. So I dug a bit further…and found this:
So the value I was capturing from the user was still being stored in the variable. Problem is, it was the wrong type of variable; it was a string, not a number (integer OR float). Incidentally, as I discovered later, I could have also checked this with ‘console.debug()’:
As such, I needed to convert the variable from a string into a number. After another bit of Googling, and as usual, with StackOverflow coming to the rescue, I discovered the ‘Number()’ function.
After this, like magic it all worked, once I’d capitalised the N in ‘Number()’…
While just a little example of overcoming obstacles in JS, there is still a lot of scope for this little Pen. Mostly, that all of the outputs are based upon outputs to the console, rather than anything actually functionally usable on a web page. Watch this space…!
Full project available on CodePen at whatever it’s state of development.