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

JavaScript Modify Object Properties

Tetsuya Uno
Tetsuya Uno
21,024 Points

total sale not shown properly

Can anyone tell me why total sale is $459.90000000000003, not $459.9?

My code:

let product = {
  name: 'bag',
  inventory: 10,
  unit_price: 45.99,
}

const addInventory = (product, num) => {
  product.inventory += num;
  console.log(`${num} ${product.name}s added to the inventory to ${product.inventory}`);
}
addInventory(product,10);

const processSale = (product, numSold) => {
  product.inventory -= numSold;
  let totalSale = product.unit_price * numSold;
  console.log(`${numSold} bags sold. Total sales is $${totalSale}`);
}

processSale(product, 10);

Returns 10 bags added to the inventory to 20
10 bags sold. Total sales is $459.90000000000003

1 Answer

Dario Bahena
Dario Bahena
10,697 Points

In most programming languages, money cannot be accurately represented by float type. For instance, in JavaScript, if you add

0.1 + 0.2 // 0.30000000000000004

which is mathematically incorrect. This has to do with how floats are added in binary and accuracy is compromised for speed.

solutions:

  1. ignore the accuracy issue and use the toPrecision method
  2. use a currency addition library (this is whats done in actual production)
  3. implement your own currency safe arithmetic algorithm (tip: use strings instead of numbers and convert between)

For this particular problem, it's ok to just use solution 1.

let product = {
  name: 'bag',
  inventory: 10,
  unit_price: 45.99,
}

const addInventory = (product, num) => {
  product.inventory += num;
  console.log(`${num} ${product.name}s added to the inventory to ${product.inventory}`);
}
addInventory(product,10);

const processSale = (product, numSold) => {
  product.inventory -= numSold;
  let totalSale = product.unit_price * numSold;
  console.log(`${numSold} bags sold. Total sales is $${totalSale.toPrecision(2)}`);
}

processSale(product, 10);
Tetsuya Uno
Tetsuya Uno
21,024 Points

Thank you for the answer! It's all clear now.