Java RegEx – Remove Decimal Part From the Number

Java RegEx – remove the decimal part from the number example shows how to remove decimal point and decimal part from a number using the regex pattern.

How to remove the decimal point and decimal part from a number using regex?

In order to remove the decimal point and trailing decimal parts or trailing zeros, we need to use the replaceAll method along with the regex pattern. We are going to replace the matching text with the empty string to remove it from the number.

I am going to use the below-given pattern to remove the decimal point and decimal part from the number.

Where,

We need to escape the dot “.” because in regex it means any characters if unescaped. Let’s try our pattern with some example numbers.

Output

As you can see from the output, we successfully replaced the decimal point and trailing numbers from the string using our pattern. But how about an invalid number like “.12”? Well, the pattern will still remove that from the string. In order to fix it, we need to make sure that there is at least one digit before the decimal point. If it does not, we do not want to remove that as given below.

Output

In the above pattern, I have used a positive lookbehind expression to check that the dot is preceded by at least one digit.

If you want to learn more about regular expression, please visit the Java RegEx tutorial.

Please let me know your views in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *