JQuery Calculation returns NaN
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开发者_如何学Python the calculation is invalid (eg. when dividing by zero) and display an empty string instead.
Greatly appreciate any help. Cheers!
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) + "%" : "";
});
}
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.
精彩评论