将字符串转换为int以进行求和,然后在必要时使用逗号返回字符串

时间:2013-04-09 18:17:22

标签: java string int

我有一些数字表示为字符串。其中一些格式如下,“12,309”。我需要将它们更改为整数,然后将它们相加,然后在适当的位置用逗号将它们更改回字符串。我该怎么做呢?

2 个答案:

答案 0 :(得分:3)

使用DecimalFormat类指定带逗号的格式。使用parse方法将String解析为Number,使用format方法将其转换为带逗号的String

格式字符串“#,###”应足以表示以逗号分隔的数字,例如1,234,567。

答案 1 :(得分:0)

对空格分隔的字符串使用正则表达式,这将起作用

String regex = "(?<=[\\d])(,)(?=[\\d])";
Pattern p = Pattern.compile(regex);

String str = "12,000 1,000 42";

int currentInt = 0;
int sum = 0; 
String currentStr = "";

for(int i = 0; i < commaDelimitedNumbers.length; i++){

    currentStr = commaDelimitedNumbers[i];

    Matcher m = p.matcher(currentStr);

    currentStr = m.replaceAll("");

    currentInt = Integer.parseInt(currentStr);

    sum  += currentInt;
}

System.out.println(sum);
相关问题