views:

304

answers:

2

I'm using JQuery Calculation plugin with the following script:

function recalc() {
         jQuery("input[class^=percent]").calc(
            "(invoice - cost)/invoice * 100",
            {
                invoice: jQuery("input[class^=invoice]"),
                cost: jQuery("input[class^=cost]")
            },
                function(s) {
                // return the number as a perrcent amount
              return s.toFixed(2) + "%";
            }
        )
    };

Just wondering how to stop "NaN%" being displayed when the calculation is invalid (eg. when dividing by zero) and display an empty string instead.

Greatly appreciate any help. Cheers!

+2  A: 

To avoid showing "NaN%", you can simply check if the s argument isNaN, and return an empty string, otherwise return the number:

function recalc() {
  jQuery("input[class^=percent]").calc("(invoice - cost)/invoice * 100", {
    invoice: jQuery("input[class^=invoice]"),
    cost: jQuery("input[class^=cost]")
  },
  function(s) {
    // return an empty string if s is NaN
    return !isNaN(s) ? s.toFixed(2) + "%" : "";
  });
}
CMS
Great, worked a treat, thanks CMS!
Paul
+1  A: 

A more proactive approach might be to prevent the NaN from happening in the first place. Doing checks before performing the calculation allows you to provide better feedback when (before) something goes wrong. Maybe that's overkill for what you're doing, but its better practice to prevent exceptional situations.

brian