0

var precision = !!values.amountprecision && values.amountprecision || '2';
var temp = /^\d+(\.\d{1,2})?$/;
temp.test(1.1221);

In the above expression, i have explicitly mentioned 1 to 2 values after decimal points. but i want to set the digits after decimal point should be based on the precision variable.

Rohini S
  • 13
  • 1
  • Testing numbers coerced to strings using regular expressions makes me go ick. What would you say is the precision of [`0.1 + 0.2`](https://stackoverflow.com/questions/588004/is-floating-point-math-broken)? At least round them to like five or six digits so you lose the artifacts near epsilon. Also, if you demand precision 2, `1.7` will always fail (since `1.70` will auto-coerce to `"1.7"`, not `"1.70"`). I answered the question about how to embed dynamic things into regexp; but unless you're doing something weird and wonderful that I didn't expect, you're probably want to rethink your approach. – Amadan Oct 16 '18 at 10:31

2 Answers2

1

Use the excplicit constructor instead of the literal:

var temp = new RegExp('^\d+(\.\d{' + precision + '})?$');
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

According your code 「var temp = /^\d+(.\d{1,2})?$/;」, I guess you need an integer or a float with 1 or 2 digits after the decimal point. And the number of digits determined by a variable, precision. If so, try this

let temp = new RegExp(`^\\d+(\\.\\d{${precision}})?$`);

ChengWei
  • 46
  • 5