Hoinzey

Javascript. Kotlin. Android. Java

Just build it: Bill & Tip splitter

Just build it

You tend to be better at the things you do more often. You tend not to show off what you are not good at but that is what these posts are about. I'm going to take bite-sized problems in languages I do and do not work in and tackle them and then post them. This is in an effort to become a better programmer and engineer because if I do not practice the action of writing code I can't honestly expect to get better at it.


So for the first post in this series I am doing a cliché starter app: A tip calculator. In javascript. Why ? Because it is simple and I don't use javascript in my day job.


Disclaimer: the code you are going to find in these posts is never going to be optimal, that just isn't the point.


The problem

Write some javascript to determine how much each member of a party must pay at the end of a meal after a tip has been added to the cost.
So we have the following variables:

  • The total bill
  • How much we want to tip
  • The number of people

You can find the rest of the code (html) here

                    
    console.log('Tip me !')
    var numberOfPeople = document.getElementsByName("peoplecount")[0].value
    var originalBill = document.getElementsByName("billtotal")[0].value
    var tipPercent = document.getElementsByName("tippercent")[0].value
    var totalPerPerson = document.getElementById("costpp")

    var tipAsNumber = (Number.parseFloat(tipPercent) / 100)
    var totalBill = Number.parseFloat(originalBill) + (originalBill * tipAsNumber)

    var costPerPerson = (totalBill / numberOfPeople).toFixed(2)
    totalPerPerson.textContent = costPerPerson
        
    console.log("For "+numberOfPeople+ " people the bill of "+originalBill + "\n"
    + "with a tip of " + tipPercent+"% brings the per-person cost to \n"
    + costPerPerson)
                

And that's it. Provided each person in the party cost the exact same amount for their meal you have a perfectly fair way to know how much is owed per person including with the tip. Happy eating comrades.