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.
1 |
\\.\\d+$ |
Where,
1 2 3 |
\\. - Means a dot character \\d+ - Followed by any digit one or more times $ - End of the string |
We need to escape the dot “.” because in regex it means any characters if unescaped. Let’s try our pattern with some example numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.javacodeexamples.regex; public class RegExRemoveDecimalPart { public static void main(String[] args) { String[] strNumbers = { "100", "100.1", "100.00", "100.1234" }; for(String strNumber : strNumbers) { System.out.println( strNumber + " => " + strNumber.replaceAll("\\.\\d+$", "") ); } } } |
Output
1 2 3 4 |
100 => 100 100.1 => 100 100.00 => 100 100.1234 => 100 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.javacodeexamples.regex; public class RegExRemoveDecimalPart { public static void main(String[] args) { String[] strNumbers = { "100", "100.1", "100.000000", ".01" }; for(String strNumber : strNumbers) { System.out.println( strNumber + " => " + strNumber.replaceAll("(?<=\\d+)\\.\\d+$", "") ); } } } |
Output
1 2 3 4 |
100 => 100 100.1 => 100 100.000000 => 100 .01 => .01 |
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.