Using RegEx how to remove trailing zeros from a decimal

I need to write some regex that takes a number and removes any trailing zeros after the decimal point. The language is ActionScript 3. So I would like to write:

var result:String = theStringOfTheNumber.replace( [ the regex ], "" );

      

So for example:

3.04000

will be 3.04

0.456000

will be 0.456

, etc.

I've spent some time on various regex websites and it's hard for me to work it out than I originally thought.

+3


source to share


8 answers


Regex:

^(\d+\.\d*?[1-9])0+$

      

OR

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

      

Replaced string:



$1

      

DEMO

Code:

var result:String = theStringOfTheNumber.replace(/(\.\d*?[1-9])0+$/g, "$1" );

      

+3


source


(?=.*?\.)(.*?[1-9])(?!.*?\.)(?=0*$)|^.*$

      

Try it. Capture the capture. See demo.



http://regex101.com/r/xE6aD0/11

+2


source


How about removing trailing zeros before the \b

border if there is at least one digit after.

(\.\d+?)0+\b

      

And replace with what was written in the first group.

$1

      

See the test at regexr.com

+2


source


This regex is used:

(\d*)((\.0*$)|(\.[1-9]*)0*$)

      

Replaced by:

$1$4

      

+1


source


try it

^(?!0*(\.0+)?$)(\d+|\d*\.\d+)$

      

And read this http://www.regular-expressions.info/numericranges.html might be helpful.

0


source


I know this is not what the original question is looking for, but anyone looking to format money and would only want to remove two consecutive trailing zeros, like this:

£30.00 => £30
£30.10 => £30.10 (and not £30.1)

30.00€ => 3030.10€ => 30.10
      

You should then be able to use the following regex, which will identify two trailing zeros followed by no other digit, or exist at the end of the string.

([^\d]00)(?=[^\d]|$)

      

0


source


If your regex engine does not support the "lookaround" feature, you can use this simple approach:

fn:replace("12300400", "([^0])0*$", "$1")

      

The result will be: 123004

0


source


Do you really need to use a regular expression? Why not just check the last digits in your numbers? I'm not familiar with ActionScript 3, but in python I would do something like this:

decinums = ['1.100', '0.0','1.1','10']
for d in decinums:
    if d.find('.'):
        while d.endswith('0'):
            d = d[:-1]
    if d.endswith('.'):
        d = d[:-1]
    print(d)

      

The result will be:

1.1
0
1.1
10

      

0


source







All Articles