Search code examples
regexregexp-replace

Regex to add a 0 to the 2nd digit after comma if missing


I want to add a 0 to the 2nd digit after comma in case it's missing. For example: Having the values -2,3; 45,5; 3.000,0; and replacing to -2,30; 45,50; 3.000,00. I thought about matching with .*,\d{1} in an IF statement first (i.e. checking if the value has just 1 digit after the comma) and then replacing with the pattern (.*) and replace function ${1}0, but this seems to be adding two zeroes instead of one, e.g. resulting into -2,300; 45,500, etc..

Edit: I just realized that I could also just concatenate the string with a "0" if regex matching returns true.


Solution

  • You do not need to check if a string ends with a comma and one digit. You can use

    (,\d)$
    

    Replace with ${1}0.

    See the regex demo.

    Now, the consuming part will never match an empty string and will match

    • (,\d) - a comma and a digit (Capturing group 1)
    • $ - end of string.

    ${1}0 will replace the match with the Group 1 value with 0 after it .