英文:
How to check and set if/else condition that a value is only has two decimal points?
问题
我正在编写一个函数,需要确保所有输入在执行任何操作之前都是正确的。其中一件事是检查一个数字中是否恰好有2个小数点。我不知道如何在if/else条件中编写这个检查。
例如:
2.22 = true
1.00 = true
10.32 = true
100.11 = true
12.1 = false
1.044 = false
我目前的函数检查是否存在小数点,以及值是否为数字,如下所示:
else if (data === "" || !data.includes('.') || isNaN(data) || data.split(".")[1].length > 3) {...}
我该如何做这个检查?
英文:
i'm writing a function and need to ensure that all of the inputs are correct before I do anything with them. one thing I need to do is check whether there are exactly 2 decimal points in a number. i can't figure out how to write this in an if/else condition.
for example:
2.22 = true
1.00 = true
10.32 = true
100.11 = true
12.1 = false
1.044 = false
I currently have the function checking that there is a decimal point, and that the value is a number like this:
else if (data === "" || !data.includes('.') || isNaN(data) || !data=.split(".")[1].length > 3)) {...}
how would I go about doing this??
答案1
得分: 1
To accomplish this, use the JavaScript Split method. This method splits a string into an array based on the decimal point. Then you can check whether the second element (that is, the fractional part) of the split array has length 2.
function checkTwoDecimalPoints(data) {
var dataString = data.toString();
if (dataString === "" || !dataString.includes('.') || isNaN(data)) {
return false;
}
else {
var decimalPart = dataString.split(".")[1];
if (decimalPart.length === 2) {
return true;
}
else {
return false;
}
}
}
英文:
To accomplish this, use the JavaScript Split method. This method splits a string into an array based on the decimal point. Then you can check whether the second element (that is, the fractional part) of the split array has length 2.
function checkTwoDecimalPoints(data) {
var dataString = data.toString();
if (dataString === "" || !dataString.includes('.') || isNaN(data)) {
return false;
}
else {
var decimalPart = dataString.split(".")[1];
if (decimalPart.length === 2) {
return true;
}
else {
return false;
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论