Remove Comma from Number in Java [2 ways]

In this post, I will be sharing how to remove comma from a number in Java. There are two ways to achieve our goal of removing commas from a number:

1. Using replace() method

2. Using replaceAll() method

Read Also: Convert Comma-Separated String to List in Java

Remove Comma from Number in Java

1. Using replace() method


We can easily remove the comma from a number using replace() method in Java as shown below in the example:

public class RemoveCommaFromNumber {
    public static void main(String args[]) {
        String str1 = "123,456,789,0987,65";
        str1 = str1.replace(",","");
        System.out.println("Remove comma from number using replace method: "+ str1);
    }
}


Outcome:
Remove comma from number using replace method: 123456789098765


2. Using replaceAll() method


We can easily remove the comma from a number using replaceAll() method in Java as shown below in the example:

public class RemoveCommaFromNumber2 {
    public static void main(String args[]) {
        String str2 = "123,456,789,0987,65";
        str2 = str2.replaceAll(",","");
        System.out.println("Remove comma from number using replaceAll method: "+ str2);
    }
}


Outcome:
Remove comma from number using replaceAll method: 123456789098765


That's all for today. Please mention in the comments if you have any questions related to how to remove comma from a number in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry