我學習BigDecimal和我希望它恢復我進入確切的數字,下面的代碼是圓棒的數量,我不知道爲什麼的Java的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
我得到'0.39000000' ... – Nivas
我剛剛運行您的代碼,我得到了。 '0.390000000000'也許你忘了保存? – Dima