I am reading some values from mongodb and then i have some options that increase the price. there are 2 type of options single and multiple. if single all the operations run smoothly. if multiple when i am reading the value (eg "1.3" ) parse float returns 1.4000001 the code that does this is the following :
this.item.productPrice = parseFloat(this.item.productPrice) -
parseFloat(a.price);
and
this.item.productPrice = parseFloat(this.item.productPrice) + parseFloat(a.price);
using debugger at the beginning of the line item.productPrice is 1.3 but after the parsing it becomes 1.4000001 and adds the a.price
the full codeblock
//this one takes the selection and adds it to selectedparams array
selected(ev: any) {
debugger;
const a = JSON.parse(ev);
if (a.multiple) {
if (Array.isArray(this.selectedparams[a.paramName])) {
const va = !a.value;
const index = this.objectinArray(this.selectedparams[a.paramName], {
option: a.option,
price: a.price,
value: va
});
if (index !== -1) {
this.item.productPrice = parseFloat(this.item.productPrice) - parseFloat(a.price);
this.selectedparams[a.paramName].splice(index, 1);
this.zone.run(() => {});
} else {
this.selectedparams[a.paramName].push({ option: a.option, price: a.price, value: a.value });
this.item.productPrice = parseFloat(this.item.productPrice) + parseFloat(a.price);
this.zone.run(() => {});
}
} else {
this.selectedparams[a.paramName] = [];
this.selectedparams[a.paramName].push({ option: a.option, price: a.price, value: a.value });
this.item.productPrice = this.item.productPrice + parseFloat(a.price);
console.log('hereeeeeeeeeeeeeeeee', this.item.productPrice);
this.zone.run(() => {});
}
} else {
this.selectedparams[a.paramName] = { selected: a.selected, price: a.price };
}
this.calcPrice();
}
//this one dows the calculation after adding
calcPrice() {
const keys = Object.keys(this.selectedparams);
console.log(this.item);
let newprice = this.item.productPrice;
keys.forEach(el => {
if (Array.isArray(this.selectedparams[el])) {
this.selectedparams[el].forEach((i: any) => {
newprice = newprice + parseFloat(i.price);
});
} else {
newprice = newprice + parseFloat(this.selectedparams[el].price);
}
});
this.showPrice = newprice;
}
TLDR(math behind) - You could use the .toFixed() function:
var result = parseFloat('0.1') + parseFloat('1.3');
console.log(result.toFixed(1)); // 1.4
var result = parseFloat('0.1') + parseFloat('1.3');
console.log(result); // 1.400000001