最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regular Expression for Currency - Stack Overflow

programmeradmin7浏览0评论

I am new to Regular Expression concept.

I tried to make currency regular expression in which

  1. Amount should be a formatted number string, using ‘,’ for the thousands separator and ‘.’ for the decimal separator.

  2. Amount should have exactly 2 decimal places

  3. Amount should be a nonzero,positive value

I tried this

test1= /^\d{1,3}?([,]\d{3}|\d)*?\.\d\d$/;
test1.test(1,100.00);

But its not fulfilling my requirements.Suggest me how e i achieve this.

I am new to Regular Expression concept.

I tried to make currency regular expression in which

  1. Amount should be a formatted number string, using ‘,’ for the thousands separator and ‘.’ for the decimal separator.

  2. Amount should have exactly 2 decimal places

  3. Amount should be a nonzero,positive value

I tried this

test1= /^\d{1,3}?([,]\d{3}|\d)*?\.\d\d$/;
test1.test(1,100.00);

But its not fulfilling my requirements.Suggest me how e i achieve this.

Share Improve this question edited Jun 2, 2016 at 14:49 Jamiec 136k15 gold badges141 silver badges199 bronze badges asked Jun 2, 2016 at 14:47 Roli AgrawalRoli Agrawal 2,4663 gold badges24 silver badges29 bronze badges 2
  • I think you tested test1.test("1,100.00");, didn't you? Try /^(?!0+\.0+$)\d{1,3}(?:,\d{3}|\d)*\.\d{2}$/.test("1,100.00") – Wiktor Stribiżew Commented Jun 2, 2016 at 14:50
  • 2 Possible duplicate of Regex currency validation – Liam Commented Jun 2, 2016 at 14:50
Add a ment  | 

2 Answers 2

Reset to default 6

If you want to disallow 0.00 value, and allow numbers without a digit grouping symbol, you can use

 /^(?!0+\.0+$)\d{1,3}(?:,\d{3})*\.\d{2}$/.test(your_str)

See the regex demo

Explanation:

  • ^ - start of string
  • (?!0+\.0+$) - negative lookahead that fails the match if the input is zero
  • \d{1,3} - 1 to 3 digits
  • (?:,\d{3})* - 0+ sequences of a ma followed with 3 digits
  • \. - a literal dot
  • \d{2} - 2 digits (decimal part)
  • $ - end of string.

document.body.innerHTML = /^(?!0+\.0+$)\d{1,3}(?:,\d{3}|\d)*\.\d{2}$/.test("1,150.25");
document.body.innerHTML += "<br/>" + /^(?!0+\.0+$)\d{1,3}(?:,\d{3}|\d)*\.\d{2}$/.test("0.25");

document.body.innerHTML += "<br/>" + /^(?!0+\.0+$)\d{1,3}(?:,\d{3})*\.\d{2}$/.test("25");
document.body.innerHTML += "<br/>" + /^(?!0+\.0+$)\d{1,3}(?:,\d{3})*\.\d{2}$/.test("0.00");
document.body.innerHTML += "<br/>" + /^(?!0+\.0+$)\d{1,3}(?:,\d{3})*\.\d{2}$/.test("1150.25");

If your minimum value is 1.00:

^[1-9]\d{0,2}(?:,\d{3})*\.\d\d$

This doesn't allow leading zeros.

发布评论

评论列表(0)

  1. 暂无评论