[英]Java BigDecimal Rounding
I am learning BigDecimal and i want it to retrieve the exact number i entered, the following code is rouding the number and i dont know why 我正在学习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;
}
If i do something like 如果我做类似的事情
public static void main(String[] args){
BigDecimal d = Test.parseFromNumberString("0.39");
System.out.println(d);
}
The value printed is 0,00 and not 0.39 打印的值是0,00,而不是0.39
Try this code: 试试这个代码:
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);
}
Is that what you want?? 那是你要的吗??
i just ran your code and i get. 我只是运行您的代码,然后我得到了。
0.390000000000
maybe you forgot to save? 0.390000000000
也许您忘记保存了?
try cleanning your project, restart your ide and recompile. 尝试清理项目,重新启动ide并重新编译。 the code should work fine
该代码应该可以正常工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.