You are viewing limited content. For full access, please sign in.

Question

Question

Form Calculation: javascript adding extra zeros

asked on May 26, 2016 Show version history

Howdy folks,

Working with LF Forms 9.2 and Javascript. Creating a PO forms which looks pretty standard...

 

 

Here's the JS I'm using, pulled it from another Answer thread..

$(document).ready(function () {
$('.cf-table-block').on('blur', 'input', sumtotal);
function sumtotal() {
var sum = 0;
$('.cf-table-block tbody tr').each(function () {
var s = 0;
s = parseNumber($(this).find('.price input').val()) * parseNumber($(this).find('.quantity input').val());
$(this).find('.subtotal input').val(s);
sum += s;
sum += parseNumber($('.tax input').val()) + parseNumber($('.shipping input').val());
});
$('.total input').val(sum);
}
function parseNumber(n) {
var f = parseFloat(n); //Convert to float number.
return isNaN(f) ? 0 : f; //treat invalid input as 0;
}
});

Odd things happens with the multiplication with certain numbers, like multiples of 3 when the Unit Cost is 5.1, 5.2, ect.

 

Any idea what's going on..?

0 0

Answer

SELECTED ANSWER
replied on May 26, 2016

This is a classic case of floating-point errors when doing calculations. Same thing happens in many situations across many programming languages. See here for a good explanation. Easiest thing in your case would probably be to just round your results and use toFixed() get the number of decimals correct.

1 0

Replies

replied on May 26, 2016

While I appreciate the information, I'm, not a programmer by any means so I'm not sure how to impliment the 'toFixed()' into the code snippiet provided by LF.

0 0
replied on May 26, 2016

One of our programmers was able to help a bit, and providing some examples of how to use the toFixed(x)...here's what worked.

 

$(document).ready(function () {
$('.cf-table-block').on('blur', 'input', sumtotal);
function sumtotal() {
var sum = 0;
$('.cf-table-block tbody tr').each(function () {
var s = 0;
s = parseNumber($(this).find('.price input').val()) * parseNumber($(this).find('.quantity input').val());
$(this).find('.subtotal input').val(s.toFixed(2));
sum += s;
sum += parseNumber($('.tax input').val()) + parseNumber($('.shipping input').val());
});
$('.total input').val(sum.toFixed(2));
}
function parseNumber(n) {
var f = parseFloat(n); //Convert to float number.
return isNaN(f) ? 0 : f; //treat invalid input as 0;
}
});

 

0 0
You are not allowed to follow up in this post.

Sign in to reply to this post.