Ruby Regex - Round Trailing Zeros

I am 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 a trailing decimal point if part of the fraction is 0. It should also return 0 when that value is. Any suggestions? thank.

+5
source share
2 answers

Try regex:

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

and replace it with:

\1

Demonstration:

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 can just do "%g" % tstto discard 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 conclusion.

+8
source

just another way

["100.0","0.00223000"].map{|x|"%g"%x}
+12
source

All Articles