0

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??

mrbob
  • 11
  • 3
  • Use regex: https://stackoverflow.com/questions/4690986/regex-needed-to-match-number-to-exactly-two-decimal-places – Swayam Shah Jun 12 '23 at 21:45
  • https://medium.com/factory-mind/regex-tutorial-a-simple-cheatsheet-by-examples-649dc1c3f285 – Swayam Shah Jun 12 '23 at 21:51
  • this doesn't work - it seems to make everything an error, regardless of whether it is the correct amount of decimal points – mrbob Jun 12 '23 at 21:53
  • 1
    If you are declaring these as numbers then it's a meaningless check (`1.00 === 1`). If you are you passing them as strings then either use a regex or simply use [`toFixed`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) to force the correct number of decimal places – pilchard Jun 12 '23 at 22:01
  • i don't want to force the correct decimal place, I want to check whether the data being inputted has a certain number of decimal places. but I ended up getting regex to work, so all is well! – mrbob Jun 12 '23 at 22:14

1 Answers1

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


MWY
  • 1,071
  • 7
  • 15