Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using RegEx how do I remove the trailing zeros from a decimal number

I'm needing to write some regex that takes a number and removes any trailing zeros after a 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 would be 3.04

0.456000 would be 0.456 etc

I've spent some time looking at various regex websites and I'm finding this harder to resolve than I initially thought.

like image 209
user2190690 Avatar asked Oct 10 '14 12:10

user2190690


People also ask

How do you remove trailing zeros from strings?

Step 1: Get the string Step 2: Count number of trailing zeros n Step 3: Remove n characters from the beginning Step 4: return remaining string.

When would you have trailing zeros in a decimal number?

Zeros to the left of the first non zero digit are not significant. more easily seen if it is written as 3.4x10-5) ~ 0.001111 has four significant figures. Trailing zeros (the right most zeros) are significant when there is a decimal point in the number.


3 Answers

Regex:

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

OR

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

Replacement string:

$1

DEMO

Code:

var result:String = theStringOfTheNumber.replace(/(\.\d*?[1-9])0+$/g, "$1" );
like image 114
Avinash Raj Avatar answered Sep 21 '22 14:09

Avinash Raj


What about stripping the trailing zeros before a \b boundary if there's at least one digit after the .

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

And replace with what was captured in the first capture group.

$1

See test at regexr.com

like image 37
Jonny 5 Avatar answered Sep 19 '22 14:09

Jonny 5


What worked best for me was

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

For example,

s.replace(/^([\d,]+)$|^([\d,]+)\.0*$|^([\d,]+\.[0-9]*?)0*$/, "$1$2$3");

This changes

1.10000 => 1.1
1.100100 => 1.1001
1.000 => 1
1 >= 1
like image 24
cdm9002 Avatar answered Sep 21 '22 14:09

cdm9002