您能否建议从不同格式的字符串数字中检索实际值的最佳方法是什么?
示例:
我希望能够传递所有这些字符串:
101,00
101.00
-101,00
-101.00
100,000.00
100.000,00
-100,000.00
-100.000,00
并从方法中获取这些返回:
101.00
101.00
-101.00
-101.00
100000.00
100000.00
-100000.00
-100000.00
我应该使用 string.replaceAll("","") 还是有更好的方法?
谢谢
最佳答案
使用全部替换是行不通的。当您需要的是找到最后一次出现的“.”时或“,”并将其用作小数位。
基于http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
public static void main(String... args) throws ParseException {
DecimalFormatSymbols dfs1 = new DecimalFormatSymbols();
dfs1.setDecimalSeparator('.');
dfs1.setGroupingSeparator(',');
DecimalFormat df1 = new DecimalFormat("#,##0.00", dfs1);
System.out.println(df1.format(-10000)+" parsed is "+df1.parse("-10,000.01"));
DecimalFormatSymbols dfs2 = new DecimalFormatSymbols();
dfs2.setDecimalSeparator(',');
dfs2.setGroupingSeparator('.');
DecimalFormat df2 = new DecimalFormat("#,##0.00", dfs2);
System.out.println(df2.format(-10000)+" parsed is "+df2.parse("-10.000,01"));
}
打印
-10,000.00 parsed is -10000.01
-10.000,00 parsed is -10000.01
关于java - 如何从 Java 中的字符串格式数字中获取实际值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10346709/