I'm facing a very strange "unrounding" issue with typescript.
I have an app using Angular 6 and ngrx/store, on which I have some products (stored as an array of objects in the store).
Each time user increment or decrement a product quantity, a corresponding action is dispatched to store, which updates product quantity and also the products total. My store state and reducer code for incrementing product quantity are shown bellow:
export interface State {
products: Product[];
total: number;
}
const initialState = {
products: [],
total: 0
};
export function productsReducer(state = initialState, action: ProductsActions) {
let updatedProducts = [];
let updatedTotal = 0;
switch (action.type) {
case INCREMENT_PRODUCT_QUANTITY:
updatedProducts = [...state.products];
updatedProducts[action.payload].quantity++;
updatedTotal = state.total + updatedProducts[action.payload].price;
return {
...state,
products: updatedProducts,
total: updatedTotal
};
}
}
So, I have a product for which the price is 214.20 and when increasing this product quantity, product total is being calculated as below:
- First increment -> total = 214.20
- Second increment -> total = 428.40
- Third increment -> total = 642.5999999999999
The issue is that products total is being calculated as 642.5999999999999, while the expected correct result is 642.60
Inspecting the variable values, the following math is occurring: 428.40 + 214.20 = 642.5999999999999
Any idea on the cause of this issue and how to solve it?
Thanks in advance!