0

FIDDLE

Problems with adding and minus a float number.

So if it starts by 0.2

0.2 + 0.2 = 0.4

0.4 + 0.2 = 0.6000000000000001 (it should be 0.6)

I found that I must use "toFixed(2)" but this is for string? What I msut change in my code in order to make it go normal:

// The button to increment the product value
$(document).on('click', '.product_quantity_up', function(e){
    e.preventDefault();
    var arrayData = $(this).data('field-qty');
    var arr = arrayData.split(';');
    for (i = 0; i < arr.length; i++) {
        console.log(arr[i]);
    }
    fieldName = arr[0];
    var currentVal = parseFloat($('input[name='+fieldName+']').val());
    var minimalVal = parseFloat($('input[name='+fieldName+']').attr("data-minimal_quantity"));

    if (!isNaN(currentVal) && currentVal < minimalVal) {
        $('input[name='+fieldName+']').val(minimalVal);
        $(this).parent().parent().find(".ajax_add_to_cart_button").attr("data-minimal_quantity",minimalVal);
    }
    else {
        $('input[name='+fieldName+']').val(currentVal + parseFloat(arr[1])).trigger('keyup');
        $(this).parent().parent().find(".ajax_add_to_cart_button").attr("data-minimal_quantity",currentVal + parseFloat(arr[1]));
    }

    $('#'+fieldName).change();



});
AndrewS
  • 1,555
  • 4
  • 20
  • 32
  • You're fiddle has the field as an so the value would be a string. Unless I'm misunderstanding your hesitancy to use toFixed. – Taplar Oct 13 '17 at 21:55
  • Possible duplicate of [Round to at most 2 decimal places (only if necessary)](https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary) – Shawn Mehan Oct 13 '17 at 21:57

1 Answers1

2

The problem you have is due to how floating point numbers store information. If you need to work with an exact number of decimals, I recomend yo work with integers and format the output to reflect the last n positions as decimals.

For example using 2 decimal places, 1.00 is actually 100.

0.2 + 0.2 = 0.4 would be done as 20 + 20 = 40

To print this to the user you parse the integer value to a string and you format the output like "0.40" (a string)

Juan
  • 5,525
  • 2
  • 15
  • 26