我有一个数学数字的ٍ字符串,我只想在数字中放一个逗号,例如:
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);但由于存在运算符“+-..”,因此获取错误。
发布于 2019-10-12 02:05:22
使用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();
}发布于 2019-10-12 01:57:07
你可以试试这段代码:
我正在使用str.toCharArray()
public static String parseResult(String str) {
StringBuilder result = new StringBuilder();
StringBuilder currentDigits = new StringBuilder();
for (char ch: str.toCharArray()) {
if (Character.isDigit(ch)) {
currentDigits.append(ch);
} else {
if (currentDigits.length() > 0) {
String output = String.format(Locale.US,"%,d", Long.parseLong(currentDigits.toString()));
result.append(output);
currentDigits = new StringBuilder();
}
result.append(ch);
}
}
if (currentDigits.length() > 0)
result.append(currentDigits.toString());
return result.toString();
}然后调用函数:
String s="(1000+2000000-5000÷90000+√5×80000)";
Log.e("s", s);
String result = parseResult(s);
Log.e("result", result);logcat:
E/s: (1000+2000000-5000÷90000+√5×80000)
E/result: (1,000+2,000,000-5,000÷90,000+√5×80,000)https://stackoverflow.com/questions/58345446
复制相似问题