【问题标题】:comma separator in a string variable [duplicate]字符串变量中的逗号分隔符[重复]
【发布时间】:2012-08-12 11:02:29
【问题描述】:

可能重复:
How can I format a String number to have commas and round?

我有一个字符串变量(即字符串格式的数字),现在我想使用逗号分隔每三位数字。我该怎么做? 我的技术是 Struts2

【问题讨论】:

标签: java struts2 csv


【解决方案1】:

使用NumberFormat:

long num = Long.valueOf("1234567890");
String numWithCommas = java.text.NumberFormat.getInstance().format(num);

编辑:

上面的代码 sn-p 将默认使用用户当前的语言环境(我猜这可能是你想要的——你希望数字以用户习惯的方式格式化)。如果要设置特定的语言环境,可以将Locale 的实例传递给getInstance()。为方便起见,Locale 类中提供了一堆静态实例:

// Always prints with comma as separator
java.text.NumberFormat.getInstance(Locale.ENGLISH).format(num);
// => 1,234,567,890

// Always prints with period as separator
java.text.NumberFormat.getInstance(Locale.GERMAN).format(num);
// => 1.234.567.890

【讨论】:

  • -1;这一切都取决于所使用的语言环境。 getInstance() 返回的 NumberFormat 使用当前的语言环境。您应该解释如何设置正确的格式。
  • maba - 你说得对,我偷懒了,没有解释语言环境。我现在用一个例子更新了它。
【解决方案2】:
    String string = "1,234,567";
    String[] splits = string.trim().split(",");
    int num = 0;
    for (String split : splits)
    {
        num = (num * 1000) + Integer.parseInt(split.trim());
    }
    System.out.println(num); // prints 1234567

【讨论】:

    【解决方案3】:

    例如:把100000转成100000

    public class number
    {
        public static void main(String args [])
        {
            double d = 123456.78;
            DecimalFormat df = new DecimalFormat("###,### ");
            System.out.
            println(df.format(d));
        }
    }
    

    【讨论】:

      【解决方案4】:

      使用StringBuilder 及其insert() 方法可以实现此目的。

      StringBuilder sb = new StringBuilder("123456987098");
      int j = sb.length();
      
      for(int i=3 ; i<j ; i=i+4){
      
             sb.insert(i,",");
      
             }
      
      System.out.println(sb.toString());
      

      【讨论】:

        猜你喜欢
        • 2015-08-11
        • 1970-01-01
        • 2023-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多