Ruby Regex to round trailing zeros

二次信任 提交于 2020-01-11 05:26:09

问题


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.


回答1:


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.




回答2:


just another way

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


来源:https://stackoverflow.com/questions/4912963/ruby-regex-to-round-trailing-zeros

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!