Absolutely Bizarre - Code works fine, unless Dish price is set to $X.95 or $X.96

OK so this is bizarre to me…

All my courses sum the price correctly, EXCEPT if a dish is priced at $X.95 or $X.96 !

See below my code for example.

Run this and you shall see.

let menu = { _courses: { appetizers: [], mains: [], desserts: [] }, get appetizers() { return this._courses.appetizers; }, set appetizers(appetizersIn) { this._courses.appetizers = appetizersIn; }, get mains() { return this._courses.appetizers; }, set mains(mainsIn) { this._courses.mains = mainsIn; }, get desserts() { return this._courses.appetizers; }, set desserts(dessertsIn) { this._courses.desserts = dessertsIn; }, get courses() { return { appetizers: this.appetizers, mains: this.mains, desserts: this.desserts, } }, addDishToCourse(courseName, dishName, dishPrice) { const dish = { name: dishName, price: dishPrice }; this._courses[courseName].push(dish); }, getRandomDishFromCourse(courseName) { const dishes = this._courses[courseName]; const randomIndex = Math.floor(Math.random() * dishes.length); return dishes[randomIndex] }, generateRandomMeal() { const appetizer = this.getRandomDishFromCourse('appetizers'); const main = this.getRandomDishFromCourse('mains'); const dessert = this.getRandomDishFromCourse('desserts'); const totalPrice = appetizer.price + main.price + dessert.price; return `Your meal is ${appetizer.name}, ${main.name}, ${dessert.name}. The price is $${totalPrice}.` } }; // menu.addDishToCourse('appetizers', 'Caesar Salad', 4.25) menu.addDishToCourse('appetizers', 'Buffalo Wings', 8.42) // menu.addDishToCourse('appetizers', 'Jazz Balls', 2.00) // menu.addDishToCourse('mains', 'Chicken Parmesan', 10.50) menu.addDishToCourse('mains', 'Steak', 12.95) // menu.addDishToCourse('mains', 'Pizza', 20.25) menu.addDishToCourse('desserts', 'Chocalate Ice Cream', 4.25) // menu.addDishToCourse('desserts', 'Vanilla Ice Cream', 4.25) // menu.addDishToCourse('desserts', 'Strawberry Ice Cream', 4.25) let meal = menu.generateRandomMeal(); console.log(meal)

8.42+12.95+4.25 = $25.62

but in this program,

8.42+12.95+4.25. = $25.619999999999997.

How this math could give a repeating decimal is beyond me.

I have commented out the other items (as this exercises functions use random) so you can replicate the issue immediately.

All help is appreciated!

Hi,
have a look at this thread on how Javascript is calculating:
https://stackoverflow.com/questions/588004/is-floating-point-math-broken

1 Like

you can use .toFixed(2) to get a string for the number that shows it to 2 decimal places to make it look nicer.

return `Your meal is ${appetizer.name}, ${main.name}, ${dessert.name}. The price is $${totalPrice.toFixed(2)}.`
2 Likes

Wow thank you for your help on this! Very interesting stuff