我想从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
最佳答案
如果你不想参与字符串(我认为这不是好的做法 - 除了创建 de BigDecimal 的部分)你可以只用数学来做:
// [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);
我知道,我的英语很糟糕。如果您能理解我想说的话,请随时纠正。谢谢。
关于java - 从Java中的Bigdecimal中提取整数和小数部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21629894/