我想编写一个函数来检查数字是否为百分比。如果是这样,那么它应该返回true。以小数表示的百分比也应该返回true。
我希望它如何表现:
/* input value ... return value */
percentage_check("21%") == true
percentage_check("21") == true
percentage_check("0.21") == true
percentage_check(21) == true
percentage_check(0.21) == true
percentage_check(121) == false //i dont allow above 100%
percentage_check(1.21) == true
percentage_check("twenty") == false
如何定义此功能?
function percentage_check(n) {
//code
}
答案 0 :(得分:2)
这将有效:
function percentage_check(n) {
if(n.toString().match(/^\d+\.?\d?\d?%?$/) && parseFloat(n)<=100 && parseFloat(n)>=0){
return true;
}
return false;
}
答案 1 :(得分:1)
function percentage_check(n) {
return (('' + n).match(/^\d+\.?\d*%?$/) || false) && parseFloat(n) >= 0 && parseFloat(n) <= 100;
}
document.write(percentage_check("21%") + '<br>'); // == true
document.write(percentage_check("21") + '<br>'); // == true
document.write(percentage_check("0.21") + '<br>'); // == true
document.write(percentage_check(21) + '<br>'); // == true
document.write(percentage_check(0.21) + '<br>'); // == true
document.write(percentage_check(121) + '<br>'); // == false //i dont allow above 100%
document.write(percentage_check(1.21) + '<br>'); // == true
document.write(percentage_check("twenty") + '<br>'); // == false
document.write(percentage_check("21Eur") + '<br>'); // == false