How to remove NaN when there's no value entered in a field while calculating using Javascript

Viewed 117
    var discount_amount = parseFloat($('#amtdelivary').val());
    var other_discount = parseFloat($('#othdis').val());
    calculate_total_amount=Math.round(sub_total1 + tax_amount +discount_amount-other_discount);
    $('#fnltot').val(calculate_total_amount);

When I keep the other_discount text field empty, its showing a NaN. If the text field is 0 its functioning accurately but when the field is set to empty, its resulting in NaN.

    if(isNaN(other_discount)){
                other_discount=0;
            }

I tired these but its not working.

3 Answers

Append || 0 after your parseFloat like below. If value returned as NaN or any falsy value then it will return 0 instead of NaN.

var discount_amount = parseFloat($('#amtdelivary').val()) || 0;
var other_discount = parseFloat($('#othdis').val()) || 0;

var discount_amount = parseFloat();
console.log(discount_amount);

// Your if condition should also work.
if(isNaN(discount_amount)) {
  discount_amount = 0;
}
console.log(discount_amount);

// Alternate and single line solution.
discount_amount = parseFloat() || 0;
console.log(discount_amount);

In java script simple you can pass parameter in given function if true then NUMBER and if false then NOT A NUMBER.

  function IsNaN(value) {
        if (Number.isNaN(parseInt(value)) === true)
            return true;
        return false;
    }

Try this

if (other_discount == '' || other_discount ==  null) {
    other_discount = 0
}
Related