Javascript 如何检查字符串是否为浮点数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12467542/
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-08-23 08:02:35  来源:igfitidea点击:

How can I check if a string is a float?

javascriptparsing

提问by Nate Pet

I am passing in a parameter called value. I'd like to know if value is a float. So far, I have the following:

我正在传递一个名为 value 的参数。我想知道 value 是否是浮点数。到目前为止,我有以下几点:

if (!isNaN(value))
{
    alert('this is a numeric value but not sure if it is a float.');
}

How do I go one step further and convert the string to something that can evaluate to a float?

我如何更进一步并将字符串转换为可以计算为浮点数的内容?

采纳答案by Nelson

Like this:

像这样:

if (!isNaN(value) && value.toString().indexOf('.') != -1)
{
    alert('this is a numeric value and I\'m sure it is a float.');
}?

回答by Mangiucugna

You can use the parseFloat function.

您可以使用 parseFloat 函数。

If the value passed is a float, the function returns the value, otherwise it will return NaN.

如果传递的值为浮点数,则函数返回该值,否则将返回 NaN。

Something like:

就像是:

val = parseFloat(val);
if(isNaN(val))
    alert("not a float!");

回答by Nikola Radosavljevi?

Following functions also check for format. E.g. JavaScript native parseIntand parseFloatfunctions also parse strings containing non numeric characters, and functions above have consequences of this.

以下函数还会检查格式。例如 JavaScript 本机parseIntparseFloat函数也解析包含非数字字符的字符串,上面的函数会产生这种后果。

// For example, following code will work
var n = parseInt('123asd');
n == 123

These functions will return falsefor such string.

这些函数将返回false此类字符串。

function isFloat(val) {
    var floatRegex = /^-?\d+(?:[.,]\d*?)?$/;
    if (!floatRegex.test(val))
        return false;

    val = parseFloat(val);
    if (isNaN(val))
        return false;
    return true;
}

function isInt(val) {
    var intRegex = /^-?\d+$/;
    if (!intRegex.test(val))
        return false;

    var intVal = parseInt(val, 10);
    return parseFloat(val) == intVal && !isNaN(intVal);
}

回答by Yasas Rangika

To check if a string is an integer or a float

检查字符串是整数还是浮点数

function isFloat(n) {
    return parseFloat(n.match(/^-?\d*(\.\d+)?$/))>0;
}

//alert(isFloat("3.444"));

回答by Powerslave

Number.prototype.isFloat = function() {
    return (this % 1 != 0);
}

Then you can

然后你可以

var floatValue = parseFloat("2.13");
var nonFloatValue = parseFloat("11");

console.log(floatValue.isFloat()); // will output true
console.log(nonFloatValue.isFloat()); // will output false

Values like 2.00cannot really be considered float in JS, or rather every number is a float in JS.

像这样的值2.00在 JS 中不能真正被认为是浮点数,或者更确切地说,每个数字都是 JS 中的浮点数



编辑:忘记提及扩展内置类型的原型被认为是一个糟糕的做法(有充分的理由),并且不鼓励在生产环境中使用它。您仍然可以将此检查实现为普通函数

回答by maksbd19

In my case a very simple regex did the trick.

在我的情况下,一个非常简单的正则表达式成功了。

I needed to validate an user's input whether the input is a valid monetary value. I simply used-

我需要验证用户的输入是否为有效的货币值。我只是用-

/^[0-9]+(\.)?[0-9]*$/.test(number)

everything between //is the Regular Expression.

之间//的一切都是正则表达式。

/^means the match starts from the beginning of the word and $/means the match ends with the word. If you think the word can not start with the letter 0then the expression would be like [1-9][0-9]*

/^表示匹配从单词的开头开始,$/表示匹配以单词结束。如果你认为这个词不能以字母开头,0那么表达式应该是[1-9][0-9]*

[0-9]+means the word must start with at least one number.

[0-9]+表示该词必须以至少一个数字开头。

Note: *means zero or more, +means one or more and ?means one or none.

注:*表示零个或多个,+表示一个或多个,?表示一个或无。

Up to here the expression is /^[1-9][0-9]*$/and this would validate only the integer numbers.

到这里为止,表达式是/^[1-9][0-9]*$/,这将仅验证整数。

To test for a period (.) in the number we need to use \.with the expression. .is a special character which matches everything, \.will only match the period.

要测试数字中的句点 (.),我们需要\.与表达式一起使用。.是匹配所有内容的特殊字符,\.只会匹配句点。

Finally another character class [0-9]*would match with zero or more digits.

最后,另一个字符类[0-9]*将与零个或多个数字匹配。

Test Cases

测试用例

/^[0-9]+(\.)?[0-9]$/.test("21.38a") // ==> false
/^[0-9]+(\.)?[0-9]$/.test("21.38") // ==> true
/^[0-9]+(\.)?[0-9]$/.test("y2781.68") // ==> false
/^[0-9]+(\.)?[0-9]$/.test("2781r.68") // ==> false

回答by Adithya Sai

Use This:

用这个:

var isNumber = /^\d+\.\d+$/.test(value);

回答by prmph

function checkFloat(value) {
    let parsed = Number.parseFloat(value);
    return (!Number.isNaN(parsed)) && (!Number.isInteger(parsed))
}

回答by rodrigomelo

To check if a string is a float (avoid int values)

检查字符串是否为浮点数(避免 int 值)

function isFloat(n) {
   if( n.match(/^-?\d*(\.\d+)?$/) && !isNaN(parseFloat(n)) && (n%1!=0) )
      return true;
   return false;
}

var nonfloat = isFloat('12'); //will return false
var nonfloat = isFloat('12.34abc'); //will return false
var float = isFloat('12.34'); //will return true

回答by Andron

If you need to check if value is int or float:

如果您需要检查 value 是 int 还是 float:

function isFloatOrInt(n) {
    return !isNaN(n) && n.toString().match(/^-?\d*(\.\d+)?$/);
}