Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 661
sa125 Avatar asked Feb 06 '11 11:02

sa125


2 Answers

just another way

["100.0","0.00223000"].map{|x|"%g"%x}
like image 124
kurumi Avatar answered Oct 09 '22 18:10

kurumi


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.

like image 38
Bart Kiers Avatar answered Oct 09 '22 18:10

Bart Kiers