How to convert string numbers into comma separated integers in java?

15,043

Solution 1

I assume 123455 is a String.

String s = 123455;
String s1 = s.substring( 0 , 1 );  // s1 = 1 
String s2 = s.substring( 1 , 3 );  // s2 = 23
String s3 = s.substring( 2 , 7 );  // s3 = 455
s1 = s1 + ',';
s2 = s2 + ',';
s = s1 + s2;   // s is a String equivalent to 1,23,455 

Now we use static int parseInt(String str) method to convert String into integer.This method returns the integer equivalent of the number contained in the String specified by str using radix 10.

Here you cannot convert s ---> int . Since int does not have commas.If you try to convert you will get the following exception java.lang.NumberFormatException

you should use DecimalFormat Class. http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html

Solution 2

int someNumber = 123456;
NumberFormat nf = NumberFormat.getInstance();
nf.format(someNumber);

Solution 3

use java.text.NumberFormat, this will solve your problem.

Solution 4

Finally I found an exact solution for my needs.

import java.math.*;
import java.text.*;
import java.util.*;
public class Mortgage2 {
    public static void main(String[] args) {
        BigDecimal payment = new BigDecimal("1115.37");
        NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US); 
        double doublePayment = payment.doubleValue();
        String s = n.format(doublePayment);
        System.out.println(s);
    }
}
Share:
15,043
sathish
Author by

sathish

Updated on June 21, 2022

Comments

  • sathish
    sathish almost 2 years

    Can any one give me some predefined methods or user defined methods to convert string numbers(example: 123455) to comma separated integer value (example: 1,23,455).

  • sathish
    sathish almost 13 years
    first i would like to thank you all for your quick reply. my intention, for example if the string 1234 converts to currency then it will become like $1,234. if string is 123456 then currency format is $1,23,456 . i need this format.
  • CQM
    CQM about 9 years
    @sathish To format a number for a different Locale, specify it in the call to getInstance. NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH) so if you want an Indian locale, there might be one for that