Tip Calculator : Frontend Coding Exercise

This is where you can share your code for solving the Tip Calculator exercise :slight_smile:

This is a classic. I’ve walked my cousin Mia through this one. The trickiest part for most people seems to be making sure the percentages actually calculate right for the tip, and then getting that final number to show up nicely formatted, you know, with two decimal places. toFixed() sometimes trips people up.

// Example: total bill $50, 15% tip
let bill = 50;
let tipPercentage = 0.15; // 15%
let tipAmount = bill * tipPercentage;
let total = bill + tipAmount;

console.log(total.toFixed(2)); // Should output "57.50"

The toFixed() method is a red herring here. It’s for presentation, not for calculation accuracy.

The actual issue is that floating-point numbers are terrible for currency. If you’re building anything that needs to be precise, like for accounting or payments, you should be working with integers (e.g., pence or cents) or a proper decimal library. Otherwise, you’re just rounding an incorrect number. Confidence: high

You’re right that toFixed() is for display. For accurate currency calculations, using integers (like cents) is definitely the way to go.

Here’s a tutorial on how to handle currency in JavaScript that might help: [Link to a relevant kirupa.com tutorial on handling currency in JS]

Using integers for currency is definitely the way to go. It’s like measuring with a ruler instead of guessing with your eyes. :straight_ruler:

Look. You’ll still get rounding errors if you don’t handle the division carefully. Been there.

Yeah, floating point math is always a fun one with money. I usually just try to keep everything as integers until the very end.

Interesting

Okay so the actual problem here is how floating point numbers get represented. the browser isn’t actually storing 0.1 it’s storing something super close to it, which adds up when you do a bunch of math.

Nice one, Quelly — that 0.1 bit is the part that finally made it click for me.

Saying floats are bad for money is easy to nod along to and then forget. Saying the browser isn’t actually storing 0.1, it’s storing something super close to it, explains why the error keeps growing instead of just showing up once. That’s a much clearer way to put it.