Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove trailing decimal point & zeroes with Regex

Tags:

java

string

regex

Is this the proper REGEX to remove trailing decimal and zeroes from a string? I can't get it to work. What am I missing?

  1. 78.000 -> 78
  2. 78.008 -> 78.008

str.replaceAll("^.0*$", "");

like image 705
Cody Avatar asked Sep 21 '11 00:09

Cody


People also ask

How do you get rid of trailing zeros after a decimal?

You can remove trailing zeros using TRIM() function.

How do I get rid of trailing zeros before decimal in Excel?

Select the adjacent cell to the number you used. Type this formula =LEFT(D1, LEN(D4)-2)*1, D4 is the cell you will remove trailing zeros from, 2 is the number of zeros you want to remove.


2 Answers

You need to escape the ., as it is a special character in Regex that matches any character. You also have to remove the ^, which anchors at the beginning of the number.

str.replaceAll("\\.0*$", "");

You can use a lookbehind if you want to make sure there is a number in front of the dot, like this:

str.replaceAll("(?<=^\\d+)\\.0*$", "");

The lookbehind (the (?<=...) part) is not a part of the match, so it will not be replaced, but it still has to match for the rest of the regex to match.

like image 97
Håvard Avatar answered Oct 15 '22 00:10

Håvard


Nope. Use this:

str.replaceAll("[.0]+$", "");
like image 44
Joseph Silber Avatar answered Oct 14 '22 22:10

Joseph Silber