Nikhil Agarwal Nikhil Agarwal - 1 year ago 69
Javascript Question

JS calculation issue

I have a simple vat calculator, but there is something funny with one of the calculation. The problem is in the last column, saying moms. e=a + d * 0.25 is correct, but the code below is not. It shows a too big number when calculating.

JS Code:

$(document).ready(function() {

$('#submit').click(function() {
//get cost and check value
var cost = $('#cost').val();
var check = $('#checkBox');

if (cost != null && cost != "") {
if (cost < 350) {
//c = a * 1
} else {
if (':checked')) {
//c = a* 1.107* 1.25
$('#total').val((cost * 1.107 * 1.25).toFixed(2));
//d = a * 0.107
$('#toll').val((cost * 0.107).toFixed(2));
} else {
$('#total').val((cost * 1.25).toFixed(2));
if ($('#toll').val() != null && $('#toll').val() != "") {
//e = (a + d) * 0.25
var moms = (cost + $('#toll').val()) * 0.25;



Answer Source

The value of input elements will always be a string. In most of your code, you're using the "cost" value in such a way that it will be implicitly converted to a number. However, the + operator is different, and will preferentially perform string concatenation to addition.

If you explicitly force the cost to be a number when you initialize it, things should work better:

var cost = +$('#cost').val();

That leading unary + operator will force the string value to be treated as a number. Now, of course, if the string doesn't look like a good number, then cost will be set to NaN, so you should check for that:

if (!isNaN(cost)) {

That can replace your current check to see if cost is not empty.

edit Sorry, you'll also need to convert the value of $('#toll').val() so that line would look like:

            var moms = (cost + +$('#toll').val()) * 0.25;

The JavaScript + operator really likes strings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download