Issue
Yesterday i was casting some strings to number and they were working, now they don't ( i even did a commit thinking that everything was ok) , i tried to cast in any other ways, but still get Nan, it looks like something is happening to the variable that i assign the values that i cast(because i print them in console.log, and they are being casted)... so what am i doing wrong?
Here's the code:
totalPrice: number;
total: number;
if (this.cart_articles) {
for (let article of this.cart_articles) {
this.totalPrice += parseFloat(article.price);
console.log(this.totalPrice);
console.log(parseFloat(article.price));
}
this.total = this.totalPrice + (this.totalPrice * 0.18);
this.iva = this.totalPrice * 0.18;
}
So i get Nan on the variables total,totalPrice and iva. But where i use console.log to show the values before assigning them to the variables, they are ok. How can i solve this? Sorry, as you can see, im new at this.
Solution
You have to initialize totalPrice with a default value, else it'll just be undefined
, and undefined
+ any number equals NaN
.
totalPrice= 0;
total = 0;
On a side node, you could make it more efficient using reduce
:
if (this.cart_articles) {
this.totalPrice = this.cart_articles.reduce((totalPrice, article) => totalPrice += parseFloat(article.price), 0);
this.total = this.totalPrice + (this.totalPrice * 0.18);
this.iva = this.totalPrice * 0.18;
}
Answered By - Supamiu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.