-1

I hope you can help me, I am capturing what is written in a component and I need that after the point comes out, it only allows me to type two more numbers

event.target.value = event.target.value.replace(/[^0-9.]+/g, '').replace(/\B(?=(\d{2})+(?!\d))/g, '.')

1.11      ✓
11.11     ✓
1.112     x   => 1.11  => replace 2->''

I only need to validate the last option in that expression so that it does not allow me to type or it is replaced with '' if I try to type something else

ari
  • 31
  • 3
  • Please read [ask]. Research on "validate decimal" gave answers: (a) [Regex for decimal with precision of 2](https://stackoverflow.com/questions/308122/simple-regular-expression-for-a-decimal-with-a-precision-of-2), (b) [Angular: Custom validation for numbers & decimals](https://stackoverflow.com/questions/44534938/angular-2-custom-validation-for-numbers-and-decimal-values#44602206). – hc_dev Jul 24 '21 at 19:00

1 Answers1

1

You don't need regex for this. Simply using Number#toFixed can limit the number of decimal places.

function validate(s){
  return parseFloat(s).toFixed(2);
}

console.log(validate(1.11));
console.log(validate(11.11));
console.log(validate(1.112));
Spectric
  • 30,714
  • 6
  • 20
  • 43