How to Convert String with Comma to Int in Java


In this example we will show how to convert a number string with a comma to Long NumberFormate class.

Source Code

package com.beginner.examples;

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

public class StringToLongExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		demo_1();
		demo_2();
		
		try {
			
		demo_3();
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		
		

	}
	public static void demo_1()
	{
		String strNum="123456789";
		
		long num=Long.valueOf(strNum);
		
		System.out.println("Demo_1: conversion successful------"+num);
		
		
	}
	public static void demo_2()
	{
		String strNum="1,222,999,666";
		
		//Separate the string with a comma
		String[] strNums=strNum.split("[,|-]+");
		
		strNum="";
		
		for(int i=0;i<strNums.length;i++)
		{
			//Reassemble the
			strNum+=strNums[i];
		}
		long num=Long.valueOf(strNum);
		
		System.out.println("Demo_2:conversion successful-----"+num);
	}
	public static void demo_3()throws ParseException
	{  
		String strNum="1,555,666";
		//Create a number formatted object
		NumberFormat nFormat=NumberFormat.getInstance(Locale.US);
		
		long num=nFormat.parse(strNum).longValue();
		
		System.out.println("Demo_3:conversion successful-----"+num);
		
	}

}

Output:

Demo_1: conversion successful------123456789

Demo_2:conversion successful-----1222999666

Demo_3:conversion successful-----1555666

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments