输入数字,将数字从个位起每三个加一个,号
例 输入454454 输出为454,454 
   输入-45467 输出为-45,467
不能使用format里方法.下面是我实现的方法,不过数字超过int范围就不能用了,求更好的办法import java.util.ArrayList;
public class NumberFormat{
String s;
ArrayList al;
public void format(long d){
al = new ArrayList();
s = String.valueOf(d);
int len = s.length();
int n=1;
int temp = 0; 
if(String.valueOf(s.charAt(0)).equals("-")){
temp=temp+1;
}
for(int i=len-1;i>=temp;i--) {
al.add(s.charAt(i));

if(n%3==0&&n!=len-1) {
al.add(",");
}
n++;

}
if(String.valueOf(s.charAt(0)).equals("-")){
al.add("-");
}
for(int i=al.size()-1;i>=0;i--) {
System.out.print(al.get(i));
}

}
public static void main(String[] args) {
(new NumberFormat()).format(-564445645);
}
}

解决方案 »

  1.   

    http://hi.baidu.com/%D1%EE%CC%EC34/blog/item/580edd0d5d096debe1fe0b55.html 骗子公司绯闻 大家小心点 ---转发
      

  2.   

    public static String format(long n) {
    StringBuilder builder = new StringBuilder(n+"");
    for(int i = builder.length()-1, count=1; i>=0; i--, count++) {
    if(count % 3 ==0) {
    builder.insert(i, ',');
    }
    }
    if(builder.charAt(0)==',') {
    builder.deleteCharAt(0);
    }else if(builder.indexOf("-,")==0) {
    builder.deleteCharAt(1);
    }
    return builder.toString();
    }楼主说的超过int范围不能用,其错误根源不在于你写的format函数,而在于你的调用语句
    System.out.println(format(1234567890123L)); //整数的后面要加个L才表示长整型
      

  3.   


    public static void format(String s) {
    List<Character> temp =new LinkedList<Character>();
    int length = s.charAt(0) == '-' ? s.length() - 1: s.length();
    int total = length % 3 == 0 ? length/3 - 1 : length / 3;
    int count = 0;
    int i = s.length()-1;
    while (total > 0) {
    temp.add(s.charAt(i));
    count++;
    if (count == 3) {
    temp.add(',');
    count = 0;
    total--;
    }
    i--;
    }
    while ( i >= 0) {
    temp.add(s.charAt(i));
    i--;
    }
    String rs = "";
    for (int j = temp.size() - 1; j >= 0; j--) {
    rs += temp.get(j);
    }
    System.out.println(rs);
    }
      

  4.   

    MessageFormat已经提供了很全面的功能,嘿嘿如数字上加逗号,保留小数点后面两位(会自动四舍五入),百分比,货币等。
    参考实例: http://www.java2s.com/Code/Java/Development-Class/MessageFormat.htm
    import java.text.MessageFormat;public class Test {
        public static void main(String[] args) {
            Object[] params = { new Integer(123), new Double(1222234.567) };
            String msg = MessageFormat.format("{0,number,percent} and {1,number,,###.##}", params);
            System.out.println(msg);
        }
    }
      

  5.   

    问题是不能用format的方法.............
      

  6.   

    这个超过long就不能用了,有无一个百亿级的?
      

  7.   

    解决方案:
        1  可以在输入的时候就只接受字符串型的数字
        2  可以使用BigDecimal暂时就想到了这两种
      

  8.   


    public static void main(String[] args) {
            String str = "1454454";
            str = str.replaceAll("(?=(\\d\\d\\d)+$)", ",");
            System.out.println(str);
        }