V
V
Vadim Stepanenko2018-03-12 00:58:53
JavaScript
Vadim Stepanenko, 2018-03-12 00:58:53

Where does the incomprehensible fractional part come from in calculations?

Hello! There is a code:

itemsAmount = 0; 

$(".to-cart").click(function(){

var itemCoast = $(this).children('.inv-tr-item').children('.inv-item-price').text();  // Вытягиваем из дива содержимое (напр. "Цена 100,23)
itemCoast = itemCoast.replace(/[^-0-9,]/gim,''); // обрезаем "цена", оставляем только цифры (100,23)
itemCoast = itemCoast.replace(/\,/g, '.'); // Меняем запятую на точку (100.23)
itemCoast = parseFloat(itemCoast); // Парсим из строки во флоат (100.23)

if ($(this).hasClass("on-cart")) { // проверяем, есть ли товар уже в корзине через .hasClass

  itemsAmount = itemsAmount - itemCoast; // из общей суммы корзины вычитаем стоимость товара

}else{
  
  itemsAmount = itemsAmount + itemCoast; // к общей сумме корзины прибавляем стоимость товара
}

$('.cart-total span').html(itemsAmount); // Выводим стоимость в спан

});

And the problem is that if you put an item in the cart for 349.39, then 304.05, and then remove the second item for 304.05 from the cart, then the cost of the cart will not be 349.39, but 349.39000000000004. I can't figure out what the problem is.
I tried rounding to hundredths, then in this case, if you add a lot of goods, and then delete everything, then the basket amount will not be zero, but -0.01 (plus or minus a couple of hundredths)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-03-12
@Vadim1899

Math in JavaScript
In general, forget about these ways of calculating the state:
Store the state model and recalculate the sum over it whenever it changes. Round numbers only after calculations.

R
Rsa97, 2018-03-12
@Rsa97

Store the price in integers (kopecks, cents, etc.). Allocate the fractional part only for display to the person.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question