javascript 检查数字字符串是否包含十进制?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9838809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:59:21  来源:igfitidea点击:

check if number string contains decimal?

javascriptregexmathdecimalsqrt

提问by monkey blot

After doing a sqrt()

执行 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.

我在想 Regex 检查小数 - 如果它包含小数,那意味着它没有均匀地根植于整数。这对我来说已经足够了。

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.

我敢打赌还有其他方法可以完成同样的事情。

回答by stefan bachert

. means any char. You have to quote the dot. "\."

. 表示任何字符。你必须引用点。“\。”

Or you could test

或者你可以测试

if (result > Math.floor(result)) {
   // not an decimal
}

回答by pimvdb

You can use the %operator:

您可以使用%运算符:

result % 1 === 0;  // rest after dividing by 1 should be 0 for whole numbers

回答by James Hill

Use indexOf():

使用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)

回答by John Sobolewski

"." has meaning in the regex syntax which is "anything" you need to escape it using "\."

“。” 在正则表达式语法中具有含义,即您需要使用“\”将其转义的“任何东西”。

回答by Vatsal

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 :)

如果它是一个字符串,我们可以使用 split 函数然后检查返回的数组的长度。如果它大于 1,它有小数点,否则没有:)。虽然这不适用于数字:(。请参阅最后一次编辑。它现在也适用于字符串:)

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 :)

希望它可以帮助某人。快乐学习:)

回答by samar ranjan Nayak

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