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

General Discussion Create an Array of Objects

Melbourne Hauk
seal-mask
.a{fill-rule:evenodd;}techdegree
Melbourne Hauk
Full Stack JavaScript Techdegree Student 2,286 Points

Excessive/incorrect decimals in computations of total value

For some reason when logging the total value to the console I get a value with a lot of decimal digits but none of the numbers used to compute were like this. Does anyone know why this might be?

Here is what was logged in the final step: [ 'potato chips', 'pretzel sticks', 'string cheese' ]
87.70000000000002

And here are my array values:

products.push(
  {
    name : 'potato chips',
    inventory : 10,
    unit_price : 4.29
  },
  {
    name : 'pretzel sticks',
    inventory : 10,
    unit_price : 3.49
  },
  {
    name : 'string cheese',
    inventory : 10,
    unit_price : 0.99
  }
)

2 Answers

Steven Parker
Steven Parker
231,184 Points

Because of how numbers are stored, very small errors may occur. One good way to handle this is to format calculation results rounded to a fixed number of decimal places when displaying it.

The ".toFixed" and ".toPrecision" methods can be useful here.

Steven Parker
Steven Parker
231,184 Points

Melbourne Hauk — Glad to help. You can mark a question solved by choosing a "best answer".
And happy coding!

Piotr Manczak
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Piotr Manczak
Front End Web Development Techdegree Graduate 29,277 Points

So let's say:

function totalValue(array){
    let t = 0;
    array.forEach(i => t += i.unit_price * i.inventory);
    return t.toFixed(2);
}

It isn't perfect but it makes things look good.