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!
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!
Share Improve this question edited Jan 15, 2010 at 1:41 Gabriel Hurley 40.1k14 gold badges63 silver badges89 bronze badges asked Jan 15, 2010 at 1:39 PaulPaul 231 gold badge1 silver badge3 bronze badges 1- that result gives the following, prior to the call of "calc": alert(jQuery("input[class^=invoice]").val() + "\n" + jQuery("input[class^=cost]").val()); – andres descalzo Commented Jan 15, 2010 at 1:44
2 Answers
Reset to default 5To 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) + "%" : "";
});
}
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.