scorpio1441
scorpio1441

Reputation: 3098

Add/subtract minutes to/from hours decimal

I'm getting error 2.7755575615628914e-17 when I try to add 15 minutes and then subtract 5 minutes 3 times. Should be zero instead. Please help.

http://jsfiddle.net/3zq4napd/

$(document).on('click', '.add', function(event) {
    var input = $('input');

    var inputVal = parseFloat($('input').val());
    var addVal = parseFloat($(this).data('num'));
    var newVal = inputVal + (addVal / 60);

    $(input).val(newVal);
});

$(document).on('click', '.sub', function(event) {
    var input = $('input');

    var inputVal = parseFloat($('input').val());
    var subVal = parseFloat($(this).data('num'));
    var newVal = inputVal - (subVal / 60);

    $(input).val(newVal);
});

Upvotes: 0

Views: 106

Answers (1)

Amadan
Amadan

Reputation: 198526

That's normal behaviour when dealing with floating point numbers: they can be exactly represented in binary, but not all of them are exactly representable in decimal. Rounding should help.

EDIT: The best way to avoid floating point error is to avoid dealing with numbers that are not exactly representable in binary form - i.e. avoiding any division except by powers of 2. Since 60 is not a power of 2, dividing by 60 will open the door for floating point error. Thus, if you can have your calculation entirely in minutes, or in seconds, or (JavaScript standard) milliseconds, you stay entirely in integral land.

(You could even count in twenty-minute blocks, because your minimal unit is 5 minutes, which is 20 / 2^2, so you're still binary-safe. But if you count in hours (i.e. sixty-minute blocks), there is a further division by 3; since fractions of 3 are not representable in binary, the error pops up.)

Upvotes: 1

Related Questions