我想从java中的bigdecimal中提取整数部分和小数部分。
我正在使用以下代码。
BigDecimal bd = BigDecimal.valueOf(-1.30)
String textBD = bd.toPlainString();
System.out.println("length = "+textBD.length());
int radixLoc = textBD.indexOf('.');
System.out.println("Fraction "+textBD.substring(0,radixLoc)+"Cents: " + textBD.substring(radixLoc + 1, textBD.length()));
我的输出为
-1和3
但我希望尾随零也是-1.30
输出应为 -1和30
答案 0 :(得分:5)
-1.30的浮点表示不准确。以下是对代码的略微修改:
BigDecimal bd = new BigDecimal("-1.30").setScale(2, RoundingMode.HALF_UP);
String textBD = bd.toPlainString();
System.out.println("text version, length = <" + textBD + ">, " + textBD.length());
int radixLoc = textBD.indexOf('.');
System.out.println("Fraction " + textBD.substring(0, radixLoc)
+ ". Cents: " + textBD.substring(radixLoc + 1, textBD.length()));
我已经在setScale上放置了一个RoundingMode来将小部分便士(如1.295“一半上升”)舍入到1.30。
结果是:
text version, length = <-1.30>, 5
Fraction -1. Cents: 30
答案 1 :(得分:4)
如果您不想参与Strings(我认为这不是一个好习惯 - 除了创建de BigDecimal的部分),您可以使用Math进行:
// [1] Creating and rounding (just like GriffeyDog suggested) so you can sure scale are 2
BigDecimal bd = new BigDecimal("-1.30").setScale(2, RoundingMode.HALF_UP);
// [2] Fraction part (0.30)
BigDecimal fraction = bd.remainder(BigDecimal.ONE);
// [3] Fraction as integer - move the decimal.
BigDecimal fraction2 = fraction.movePointRight(bd.scale());
// [4] And the Integer part can result of:
BigDecimal natural = bd.subtract(fraction);
// [5] Since the fraction part of 'natural' is just Zeros, you can setScale(0) without worry about rounding
natural = natural.setScale(0);
我知道,我的英语太可怕了。如果你能理解我想说的话,请随意纠正。感谢。
答案 2 :(得分:1)
使用String
初始化以避免浮点精度问题。然后使用setScale
设置所需的小数位数:
BigDecimal bd = new BigDecimal("-1.30").setScale(2);
String textBD = bd.toPlainString();
System.out.println("length = "+textBD.length());
int radixLoc = textBD.indexOf('.');
System.out.println("Fraction "+textBD.substring(0,radixLoc)+"Cents: " + textBD.substring(radixLoc + 1, textBD.length()));