我有一个数学数字字符串,我只想在数字中添加逗号,例如:
String s="(1000+2000000-5000.8÷90000+√5×80000)";
我想将它发送到一个方法来将其转换为
String s="(1,000+2,000,000-5,000.8÷90,000+√5×80,000)";
我正在使用:
DecimalFormat myFormatter = new DecimalFormat("$###,###.###");
String output = myFormatter.format(s);
System.out.println(output);
但是会出错,因为有运算符“+-..”
最佳答案
使用 Matcher.appendReplacement
的简单方法还不够吗?
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
....
static String formatMyString(String input){
DecimalFormat myFormatter = new DecimalFormat("###,###.###");
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile("(\\d+\\.*\\d+)");
Matcher m = p.matcher(input);
while(m.find()){
String rep = myFormatter.format(Double.parseDouble(m.group()));
m.appendReplacement(sb,rep);
}
m.appendTail(sb);
return sb.toString();
}
关于java - 在数学字符串内的数字中添加逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58345446/