check if number string contains decimal?
-
26-05-2021 - |
Question
After doing a sqrt()
How can I be check to see if the result contains only whole numbers or not?
I was thinking Regex to check for a decimal - if it contains a decimal, that means it didn't root evenly into whole numbers. Which would be enough info for me.
but this code isnt working...
result = sqrt(stringContainingANumber);
decimal = new RegExp(".");
document.write(decimal.test(result));
I bet there's other ways to accomplish the same thing though.
Solution
. means any char. You have to quote the dot. "\."
Or you could test
if (result > Math.floor(result)) {
// not an decimal
}
OTHER TIPS
You can use the %
operator:
result % 1 === 0; // rest after dividing by 1 should be 0 for whole numbers
Use indexOf()
:
var myStr = "1.0";
myStr.indexOf("."); // Returns 1
// Other examples
myStr.indexOf("1"); // Returns 0 (meaning that "1" may be found at index 0)
myStr.indexOf("2"); // Returns -1 (meaning can't be found)
"." has meaning in the regex syntax which is "anything" you need to escape it using "\."
If its a string we can just use split function and then check the length of the array returned. If its more than 1 it has decimal point else not :). This doesn't work for numbers though :(. Please see the last edit. It works for string as well now :)
function checkDecimal() {
var str = "202.0";
var res = str.split(".");
alert(res.length >1);
var str1 = "20";
alert(str1.split(".").length>1);
}
Hope it helps someone. Happy Learning :)
Are you looking for checking string containing decimal digits , you can try like this
var num = "123.677";
if (!isNaN(Number(num)) {
alert("decimal no");
}
else {
alert("Not a decimal number");
}