Java 字符串变量中的逗号分隔符
可能重复: 我有一个字符串变量,它是字符串格式的数字,现在我想用逗号分隔每三位数字。我怎么做? 我的技术是Struts2使用: 编辑: 上面的代码片段将默认使用用户的当前语言环境,我猜这可能是您想要的。您希望以用户习惯看到的方式格式化数字。如果要设置特定的区域设置,可以将的实例传递给getInstance。为了您的方便,Locale类中提供了大量静态实例:Java 字符串变量中的逗号分隔符,java,struts2,csv,Java,Struts2,Csv,可能重复: 我有一个字符串变量,它是字符串格式的数字,现在我想用逗号分隔每三位数字。我怎么做? 我的技术是Struts2使用: 编辑: 上面的代码片段将默认使用用户的当前语言环境,我猜这可能是您想要的。您希望以用户习惯看到的方式格式化数字。如果要设置特定的区域设置,可以将的实例传递给getInstance。为了您的方便,Locale类中提供了大量静态实例: // Always prints with comma as separator java.text.NumberFormat.getIn
// 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
例如:将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));
}
}
使用StringBuilder及其插入方法可以实现这一点
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());
请重新措辞你的问题。您希望在字符串中添加逗号,还是希望使用逗号拆分/分析字符串。请使用string类的split方法。请参阅-1;这完全取决于所使用的区域设置。getInstance返回的NumberFormat使用当前区域设置。你应该解释如何设置正确的格式。maba-你说得对,我放松了,没有解释语言环境。我现在用一个例子更新了它。
public class number
{
public static void main(String args [])
{
double d = 123456.78;
DecimalFormat df = new DecimalFormat("###,### ");
System.out.
println(df.format(d));
}
}
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());