Java convert string with commas to int - Java Programming Examples

Overview

In this tutorial, we show you how to convert string with comma to int in Java. We using java.text.NumberFormat class and Integer.valueOf() method with String.replaceAll() method.

Java convert string with commas to int



Convert string with comma to int using java.text.NumberFormat

package com.jackrutorial;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

public class ConvertStringWithCommaToIntExample1 {

 public static void main(String[] args) {
  String strNumber = "1,073,741,824";
  NumberFormat format = NumberFormat.getInstance(Locale.US);
  Number number = 0;
  try {
   number = format.parse(strNumber);
  } catch (ParseException e) {
   e.printStackTrace();
  }

  int num = number.intValue();

  System.out.println("String => " + strNumber);
  System.out.println("String to int => " + num);
 }
}

Output

String => 1,073,741,824
String to int => 1073741824

Convert string with comma to int using Integer.valueOf() and String.replaceAll()

package com.jackrutorial;

public class ConvertStringWithCommaToIntExample2 {

 public static void main(String[] args) {
  String strNumber = "1,073,741,824";
  System.out.println("String => " + strNumber);
  
  strNumber = strNumber.replaceAll(",", "");
  int num = Integer.valueOf(strNumber).intValue();
  
  System.out.println("String to int => " + num);
 }
}

Output

String => 1,073,741,824
String to int => 1073741824
Previous Post
Next Post

post written by: