开发者

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

Can any one give me some p开发者_如何学编程redefined methods or user defined methods to convert string numbers(example: 123455) to comma separated integer value (example: 1,23,455).


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


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


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);
    }
}


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


What you're looking for is the DecimalFormat class (here), where you can set easily separator and convert a String to a Number with the method parse() for example.


The result you expected that is "to comma separated integer value", is in my opinion incorrect. However, if you are just looking for output representation, how about these lines of codes shown below? (Note, you can not parse the value return from valueToString to some data type long because it just does not make sense :) )

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜