Search code examples
regexregex-greedy

Truncate trailing zeroes regex


How to get a match using regex to truncate zeroes in a string like this

45.9390 => 45.939
32.00 => 32.0 [Need this for my use case]
32.0050 => 32.005
32 => 32

I am using Java. I am just looking for the regex. This is my closest attempt( https://regex101.com/r/mD7gK4/79 ). I am missing on the second case.


Solution

  • I have edited your regex:

    ^([+-]?\d*\.0)0+$|^([+-]?\d*\.?\d*?)0*$
    

    and use \1\2 as substitution string:

    Demo: https://regex101.com/r/mD7gK4/81

    Output:

    45.9390 => 45.939
    32.00 => 32.0
    32.0050 => 32.005
    32 => 32