I have this user price input that I want to allow 0, 1 or 2 decimal digits.
- I'm using ma for decimals.
- I'm not using nor allowing thousand separators.
QUESTION:
I want to replace the input if the user enters a third decimal digit.
Somethin like:
5
this is ok5,
this is ok, because it's waiting for the decimals5,5
this is ok5,55
this is ok5,555
this is NOT OK, and I want to delete the last digit and go back to5,55
5,555555555555
this is also NOT OK, the user might paste something with extra decimal digits and I want to trim them down to 2 decimals maximum, going back again to5,55
How can I do this?
I know how I can match the end of the string: /[,\d+]$/
But how can I replace with the first two digits after the ma?
I have this user price input that I want to allow 0, 1 or 2 decimal digits.
- I'm using ma for decimals.
- I'm not using nor allowing thousand separators.
QUESTION:
I want to replace the input if the user enters a third decimal digit.
Somethin like:
5
this is ok5,
this is ok, because it's waiting for the decimals5,5
this is ok5,55
this is ok5,555
this is NOT OK, and I want to delete the last digit and go back to5,55
5,555555555555
this is also NOT OK, the user might paste something with extra decimal digits and I want to trim them down to 2 decimals maximum, going back again to5,55
How can I do this?
I know how I can match the end of the string: /[,\d+]$/
But how can I replace with the first two digits after the ma?
Share Improve this question edited May 30, 2019 at 16:57 Emma 27.8k11 gold badges48 silver badges71 bronze badges asked May 30, 2019 at 15:37 cbdevelopercbdeveloper 31.5k45 gold badges202 silver badges396 bronze badges2 Answers
Reset to default 7Your pattern [,\d+]$
will match a ma a digit or a plus sign and assert the end of the string.
You could capture in a group 1+ digits, an optional ma and 0-2 digits. then match 0+ digits afterwards and replace with group 1.
^(\d+,?\d{0,2})\d*$
Explanation
^
Start of strig(
Capture group 1\d+
1+ digits,?
optional ma\d{0,2}
0 - 2 digits
)
Close group\d*
Match 0+ digits$
Assert end of string
Regex demo
If you want to keep the part before the decimal, you could use a capturing group^(\d+),?\d{0,2}$
and replace with the first capturing group:
[
"5",
"5",
"5,0",
"5,00",
"5,000"
].forEach(s => console.log(s.replace(/^(\d+,?\d{0,2})\d*$/, "$1")));
You could always temporarily convert the ma to a period, parse the float and fix it to 2 decimals, then replace the period with a ma again like below;
let str = '1,567895'; // price value
let val = parseFloat(str.replace(',', '.')).toFixed(2).replace('.', ',');
console.log(val);