Remove Comma from Number in Java [2 ways] | Java Hungry

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:

Remove Comma from Number in Java

1. Using replace() method


We can easily remove the comma from a number using 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 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.

Posting Komentar

Lebih baru Lebih lama