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

Can someone give me some predefined methods or user-defined methods for converting string numbers (example: 123455) to the value of integers with a comma (example: 1,23,455).

+7
source share
6 answers

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 the static int parseInt(String str) method to convert String to 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 has no commas. If you try to convert, you will get the following java.lang.NumberFormatException

You must use the DecimalFormat Class. http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html

0
source
 int someNumber = 123456; NumberFormat nf = NumberFormat.getInstance(); nf.format(someNumber); 
+9
source

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

+3
source

Finally, I found the 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); } } 
+1
source

What you are looking for is the DecimalFormat class ( here ), where you can easily set the delimiter and convert the string to a number using, for example, the parse() method.

0
source

The result you expected is a "comma separated integer", in my opinion is incorrect. However, if you're just looking for an output view , what about these lines of code shown below? (Note: you cannot parse the return from valueToString value for some data type, because it just doesn't make sense :))

 MaskFormatter format = new MaskFormatter("#,##,###"); format.setValueContainsLiteralCharacters(false); System.out.println(format.valueToString(123455)); 
0
source

All Articles