6

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.

3 Answers 3

12

just another way

["100.0","0.00223000"].map{|x|"%g"%x}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is great! Your solution "%g"%x is only 6 characters!
8

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 Comments

I think it's a lot more complicated than it needs to be but it works so +1.
:), I fully agree @Mark. I glared at it a little, but can't see a short-cut though...
1

Here is bit more optimized regex solution.

Search for this regex:

(?:(\.[0-9]*[1-9])|\.)0+$

and replace with:

\1

RegEx Demo

RegEx Details:

  • (?:: Start non-capture group
    • (\.[0-9]*[1-9]): Match a dot followed by 0+ instances of any digit and then a digit 1-9. Capture this value in group #1 (to be used in replacement back-reference \1)
    • |: OR
    • \.: Match a dot
  • ): End non-capture group
  • 0+: Match 1+ of zeroes
  • $: End

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.