我正在学习BigDecimal,我想让它检索我输入的确切数字,下面的代码是对数字进行取整,我不知道为什么
public static BigDecimal parseFromNumberString(String numberString) {
if (numberString != null) {
String nonSpacedString =
numberString.replaceAll("[ \\t\\n\\x0B\\f\\r]", "").replaceAll("%", "");
int indexOfComma = nonSpacedString.indexOf(',');
int indexOfDot = nonSpacedString.indexOf('.');
NumberFormat format = null;
if (indexOfComma < indexOfDot) {
nonSpacedString = nonSpacedString.replaceAll("[,]", "");
format = new DecimalFormat("##.#");
} else if (indexOfComma > indexOfDot) {
nonSpacedString = nonSpacedString.replaceAll("[.]", "");
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols();
otherSymbols.setDecimalSeparator(',');
format = new DecimalFormat("##,#", otherSymbols);
} else {
format = new DecimalFormat();
}
try {
return new BigDecimal(format.parse(nonSpacedString).doubleValue(), new MathContext(12));
} catch (ParseException e) {
// unrecognized number format
return null;
}
}
return null;
}如果我做像这样的事情
public static void main(String[] args){
BigDecimal d = Test.parseFromNumberString("0.39");
System.out.println(d);
}打印的值是0,00,而不是0.39
发布于 2015-10-14 06:55:22
尝试以下代码:
public static BigDecimal parseFromNumberString(String numberString) {
if (numberString != null) {
String nonSpacedString =
numberString.replaceAll("[ \\t\\n\\x0B\\f\\r]", "").replaceAll("%", "");
int indexOfComma = nonSpacedString.indexOf(',');
int indexOfDot = nonSpacedString.indexOf('.');
DecimalFormat decimalFormat = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
String pattern = "#0.0#";
if (indexOfComma < indexOfDot) {
symbols.setDecimalSeparator('.');
} else if (indexOfComma > indexOfDot) {
symbols.setDecimalSeparator(',');
}
try {
decimalFormat = new DecimalFormat(pattern, symbols);
decimalFormat.setParseBigDecimal(true);
BigDecimal toRet = (BigDecimal) decimalFormat.parse(nonSpacedString);
return toRet.setScale(12);
} catch (ParseException e) {
return null;
}
}
return null;
}
public static void main(String... args) {
BigDecimal d = Test.parseFromNumberString("0,39");
System.out.println(d);
}这就是你想要的吗?
发布于 2014-04-16 02:35:15
我刚运行了你的代码然后我得到了。0.390000000000也许你忘了保存?
尝试清除您的项目,重新启动您的ide并重新编译。代码应该可以正常工作
https://stackoverflow.com/questions/23091528
复制相似问题