JavaScript 中的正则表达式用于验证十进制数

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

Regex in JavaScript for validating decimal numbers

javascriptregex

提问by Shardaprasad Soni

I want a regex in JavaScript for validating decimal numbers.

我想要一个 JavaScript 中的正则表达式来验证十进制数。

It should allow only up to two decimal places. For example, it should allow 10.89but not 10.899.

它应该只允许最多两位小数。例如,它应该允许10.89但不允许10.899

It should also allow only one period (.). For example, it should allow 10.89but not 10.8.9.

它还应该只允许一个句点 ( .)。例如,它应该允许10.89但不允许10.8.9

回答by zatatatata

Try the following expression: ^\d+\.\d{0,2}$If you want the decimal places to be optional, you can use the following: ^\d+(\.\d{1,2})?$

试试下面的表达式:^\d+\.\d{0,2}$如果你想让小数位是可选的,你可以使用下面的:^\d+(\.\d{1,2})?$

EDIT:To test a string match in Javascript use the following snippet:

编辑:要在 Javascript 中测试字符串匹配,请使用以下代码段:

var regexp = /^\d+\.\d{0,2}$/;

// returns true
regexp.test('10.5')

回答by noob

^\d+(\.\d{1,2})?$

will allow:

将会允许:

  1. 244
  2. 10.89
  3. 9.5
  1. 244
  2. 10.89
  3. 9.5

will disallow:

将不允许:

  1. 10.895
  2. 10.
  3. 10.8.9
  1. 10.895
  2. 10.
  3. 10.8.9

回答by John Slegers

Regex

正则表达式

/^\d+(\.\d{1,2})?$/


Demo

演示

var regexp = /^\d+(\.\d{1,2})?$/;

console.log("'.74' returns " + regexp.test('.74'));
console.log("'7' returns " + regexp.test('7'));
console.log("'10.5' returns " + regexp.test('10.5'));
console.log("'115.25' returns " + regexp.test('115.25'));
console.log("'1535.803' returns " + regexp.test('1535.803'));
console.log("'153.14.5' returns " + regexp.test('153.14.5'));
console.log("'415351108140' returns " + regexp.test('415351108140'));
console.log("'415351108140.5' returns " + regexp.test('415351108140.5'));
console.log("'415351108140.55' returns " + regexp.test('415351108140.55'));
console.log("'415351108140.556' returns " + regexp.test('415351108140.556'));



Explanation

解释

  1. / /: the beginning and end of the expression
  2. ^: whatever follows should be at the beginning of the string you're testing
  3. \d+: there should be at least one digit
  4. ( )?: this part is optional
  5. \.: here goes a dot
  6. \d{1,2}: there should be between one and two digits here
  7. $: whatever precedes this should be at the end of the string you're testing
  1. / /: 表达式的开始和结束
  2. ^: 后面的内容应该在你正在测试的字符串的开头
  3. \d+: 应该至少有一位
  4. ( )?: 这部分是可选的
  5. \.: 这里有一个点
  6. \d{1,2}: 这里应该有一到两位数字
  7. $: 在此之前的任何内容都应位于您正在测试的字符串的末尾


Tip

提示

You can use regexr.comor regex101.comfor testing regular expressions directly in the browser!

您可以使用regexr.comregex101.com直接在浏览器中测试正则表达式!

回答by Nisha

Numbers with at most 2 decimal places:

最多保留 2 位小数的数字:

/^\d+(?:\.\d{1,2})?$/

This should work fine. Please try out :)

这应该可以正常工作。请试试:)

回答by Andrej

Please see my project of the cross-browser filter of value of the text input element on your web page using JavaScript language: Input Key Filter. You can filter the value as an integer number, a float number, or write a custom filter, such as a phone number filter. See an example of custom filter of input of an float number with decimal pointer and limitation to 2 digit after decimal pointer:

请参阅我的项目,使用 JavaScript 语言对您网页上的文本输入元素的值进行跨浏览器过滤器:Input Key Filter。您可以将值过滤为整数、浮点数或编写自定义过滤器,例如电话号码过滤器。请参阅带有十进制指针的浮点数输入自定义过滤器的示例,并且限制为小数点后的 2 位数字:

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Input Key Filter Test</title>
 <meta name="author" content="Andrej Hristoliubov [email protected]">
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 
 <!-- For compatibility of IE browser with audio element in the beep() function.
 https://www.modern.ie/en-us/performance/how-to-use-x-ua-compatible -->
 <meta http-equiv="X-UA-Compatible" content="IE=9"/>
 
 <link rel="stylesheet" href="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.css" type="text/css">  
 <script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/Common.js"></script>
 <script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.js"></script>
 
</head>
<body>
 <h1>Float field</h1>
<input id="Float" 
 onchange="javascript: onChangeFloat(this)"
 onblur="inputKeyFilter.isNaN(parseFloat(this.value), this);"
/>
<script>
 function CreateFloatFilterCustom(elementID, onChange, onblur){
  try{
   inputKeyFilter.Create(elementID
    , onChange
    , function(elementInput, value){//customFilter
     if(value.match(/^(-?\d*)((\.(\d{0,2})?)?)$/i) == null){
      inputKeyFilter.TextAdd(isRussian() ?
        "Допустимый формат: -[0...9].[0...9] или -[0...9]e-[0...9]. Например: -12.34 1234"
        : "Acceptable formats: -[0...9].[0...9] or -[0...9]e-[0...9]. Examples: -12.34 1234"
       , elementInput);
      return false;
     }
     return true;
    }
    , onblur
   )
  } catch(e) {
   consoleError("Create float filter failed. " + e);
  }
 }
 
 CreateFloatFilterCustom("Float");
 
 function onChangeFloat(input){
  inputKeyFilter.RemoveMyTooltip();
  var elementNewFloat = document.getElementById("NewFloat");
  var float = parseFloat(input.value);
  if(inputKeyFilter.isNaN(float, input)){
   elementNewFloat.innerHTML = "";
   return;
  }
  elementNewFloat.innerHTML = float;
 }
</script>
 New float: <span id="NewFloat"></span>
</body>
</html>

Also see my page example of the input key filter

另请参阅我的输入键过滤器页面示例

回答by Paul J Abernathy

I found that I could use

我发现我可以使用

^\d+(\.\d+)?$

for more than two decimal places.

超过两位小数。

回答by Harshit Sinha

Try a regular expression like this:

试试这样的正则表达式:

(?=[^
 function CheckValidAmount() {
        var amounttext = document.getElementById('txtRemittanceNumber').value;            
        if (!(/^[-+]?\d*\.?\d*$/.test(amounttext))){
            alert('Please enter only numbers into amount textbox.')
            document.getElementById('txtRemittanceNumber').value = "10.00";
        }
    }
])(?=^([0-9]+){0,1}(\.[0-9]{1,2}){0,1}$)

Allowed:1, 10.8, 10.89, .89, 0.89, 1000

允许:1、10.8、10.89、.89、0.89、1000

Not Allowed:20. , 50.89.9, 12.999, ., Null character Note this works for positive numbers

不允许:20. , 50.89.9, 12.999, ., Null character 注意这适用于正数

回答by Bhanu Pratap

{
    "type": "string",
    "pattern": "^[0-9]+(\.[0-9]{2})?$"
}

This is the function which will take decimal number with any number of decimal places and without any decimal places.

这是一个函数,它将取具有任意小数位且没有任何小数位的十进制数。

Thanks ... :)

谢谢 ... :)

回答by Bhumin Vadalia

as compared from the answer gven by mic... it doesnt validate anything in some of the platforms which i work upon... to be precise it doesnt actually work out in Dream Viewer..

与mic给出的答案相比......它在我工作的某些平台上没有验证任何东西......准确地说,它实际上在Dream Viewer中不起作用......

hereby.. i re-write it again..which will work on any platform.. "^[0-9]+(.[0-9]{1,2})?$"..thnkss..

特此..我重新写一遍..它可以在任何平台上工作.. “^[0-9]+(.[0-9]{1,2})?$”..thnkss..

回答by Shobhit Pokhriyal

The schema for passing the value in as a string. The regex will validate a string of at least one digit, possibly followed by a period and exactly two digits:

将值作为字符串传入的架构。正则表达式将验证至少一个数字的字符串,可能后跟一个句点和两个数字:

{
    "type": "string",
    "pattern": "^$|^[0-9]+(\.[0-9]{2})?$"
}

The schema below is equivalent, except that it also allows empty strings:

下面的模式是等效的,除了它还允许空字符串:

##代码##