如何检查并设置if/else条件,以确保一个值仅具有两位小数?

huangapple go评论84阅读模式
英文:

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;
        }
    }
}


huangapple
  • 本文由 发表于 2023年6月13日 05:42:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76460499.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定