简体   繁体   English

正则表达式强制小数点后两位数

[英]Regular expression to enforce 2 digits after decimal point

I need to validate a numeric string with JavaScript, to ensure the number has exactly two decimal places.我需要使用 JavaScript 验证数字字符串,以确保该数字恰好有两位小数。

The validation will pass only if只有在以下情况下,验证才会通过

  1. the number has precisely two decimal places该数字恰好有两位小数
  2. there is at least one digit before the decimal point.小数点前至少有一位。 (could be zero) (可能为零)
  3. the number before the decimal point can not begin with more than one zero.小数点前的数字不能以超过一个零开头。

Valid numbers:有效号码:

0.01
0.12
111.23
1234.56
012345.67
123.00
0.00

Invalid numbers:无效数字:

.12
1.1
0.0
00.00
1234.
1234.567
1234
00123.45
abcd.12
12a4.56
1234.5A

I have tried the regular expression [0-9][\\.][0-9][0-9]$ , but it allows letters before decimal point like 12a4.56 .我试过正则表达式[0-9][\\.][0-9][0-9]$ ,但它允许小数点前的字母,如12a4.56

. matches any character, it does not do what you think it does.匹配任何字符,它不会做你认为它做的事情。 You have to escape it.你必须逃避它。 Also, you have two more errors;此外,您还有两个错误; try尝试

^[0-9]+\.[0-9][0-9]$

instead, or even better, use \\d for decimal digits:相反,甚至更好,使用\\d表示十进制数字:

^\d+\.\d\d$

This covers all requirements : 这涵盖了所有要求

^(0|0?[1-9]\d*)\.\d\d$
  • the number has precisely two decimal places该数字恰好有两位小数
    • Trivially satisfied due to the non-optional \\.\\d\\d$由于非可选\\.\\d\\d$

The other two conditions can be restated as follows:另外两个条件可以重新表述如下:

  • The number before the decimal points is either a zero小数点前的数字要么是零
  • or a number with exactly one zero, then a number that does not start with zero或一个正好有一个零的数字,然后是一个以零开头的数字

This is covered in these two cases:这包括在这两种情况下:

  • 0
  • 0?[1-9]\\d*

You don't need regular expressions for this.为此,您不需要正则表达式。

JavaScript has a function toFixed() that will do what you need. JavaScript 有一个函数toFixed()您的需求。

var fixedtotwodecimals = floatvalue.toFixed(2);
var values='0.12';

document.write(values.match(/\d+[.]+\d+\d/));

change value as you want and check it根据需要更改值并检查它

i used this我用过这个

^[1-9][1-9]*[.]?[1-9]{0,2}$ ^[1-9][1-9]*[.]?[1-9]{0,2}$

  • 0 not accept 0 不接受

  • 123.12 accept but 123.123 not accept 123.12 接受但 123.123 不接受

  • 1 accept 1 接受

  • 12213123 accept 12213123 接受

  • sdfsf not accept sdfsf 不接受

  • 15.12 accept 15.12 接受

  • 15@12 not accept 15@12 不接受

  • 15&12 not accept 15&12不接受

这里是:

^(0[.]+\d{2})|^[1-9]\d+[.]+\d{2}$

Try This Code试试这个代码

pattern="[0-9]*(\.?[0-9]{1,2}$)?"
  • 1 Valid 1 有效

  • 1.1 Valid 1.1 有效

  • 1.12 Valid 1.12 有效

  • 1.123 not Valid 1.123 无效

  • only number Valid只有数字有效

    pattern="[0-9]*(.?[0-9]{2}$)?"模式="[0-9]*(.?[0-9]{2}$)?"

  • 1 Valid 1 有效

  • 1.1 not Valid 1.1 无效

  • 1.12 Valid 1.12 有效

  • 1.123 not Valid 1.123 无效

  • only number Valid只有数字有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM