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 trialMelbourne Hauk
Full Stack JavaScript Techdegree Student 2,286 PointsExcessive/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
231,275 PointsBecause 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.
Piotr Manczak
Front End Web Development Techdegree Graduate 29,367 PointsSo 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.
Melbourne Hauk
Full Stack JavaScript Techdegree Student 2,286 PointsMelbourne Hauk
Full Stack JavaScript Techdegree Student 2,286 PointsAhh, I see. So it wasn't anything I did really, just a thing that happens sometimes? Good to know, thank you for the response.
Steven Parker
231,275 PointsSteven Parker
231,275 PointsMelbourne Hauk — Glad to help. You can mark a question solved by choosing a "best answer".
And happy coding!