rubyregexfractionsdecimal-point

Ruby Regex to round trailing zeros


I'm looking for a regex to remove trailing zeros from decimal numbers. It should return the following results:

0.0002300 -> 0.00023
10.002300 -> 10.0023
100.0     -> 100
1000      -> 1000
0.0       -> 0
0         -> 0

Basically, it should remove trailing zeros and trailing decimal point if the fraction part is 0. It should also return 0 when that's the value. Any thoughts? thanks.


Solution

  • Try the regex:

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

    and replace it with:

    \1
    

    A demo:

    tests = ['0.0002300', '10.002300', '100.0', '1000', '0.0', '0']
    tests.each { |tst|
      print tst, " -> ", tst.sub(/(?:(\..*[^0])0+|\.0+)$/, '\1'), "\n"
    }
    

    which produces:

    0.0002300 -> 0.00023
    10.002300 -> 10.0023
    100.0 -> 100
    1000 -> 1000
    0.0 -> 0
    0 -> 0
    

    Or you could simply do "%g" % tst to drop the trailing zeros:

    tests = ['0.0002300', '10.002300', '100.0', '1000', '0.0', '0']
    tests.each { |tst|
      s = "%g" % tst
      print tst, " -> ", s, "\n"
    }
    

    which produces the same output.