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.
source to share
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
source to share
try it
^(?!0*(\.0+)?$)(\d+|\d*\.\d+)$
And read this http://www.regular-expressions.info/numericranges.html might be helpful.
source to share
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€ => 30€
30.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]|$)
source to share
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
source to share