Java, extract just the fractional part of a BigDecimal?

笑着哭i 提交于 2019-12-03 08:04:14

问题


In Java, I'm working with the BigDecimal class and part of my code requires me to extract the fractional part from it. BigDecimal does not appear to have any built in methods to help me get the number after the decimal point of a BigDecimal.

For example:

BigDecimal bd = new BigDecimal("23452.4523434");

I want to extract the 4523434 from the number represented above. What's the best way to do it?


回答1:


I would try bd.remainder(BigDecimal.ONE).

Uses the remainder method and the ONE constant.

BigDecimal bd = new BigDecimal( "23452.4523434" );
BigDecimal fractionalPart = bd.remainder( BigDecimal.ONE ); // Result:  0.4523434



回答2:


If the value is negative, using bd.subtract() will return a wrong decimal.

Use this:

BigInteger decimal = 
                bd.remainder(BigDecimal.ONE).movePointRight(bd.scale()).abs().toBigInteger();

It returns 4523434 for 23452.4523434 or -23452.4523434


In addition, if you don't want extra zeros on the right of the fractional part, use:

bd = bd.stripTrailingZeros();

before the previous code.




回答3:


Here's an alternative to using the remainder() method:

BigDecimal bd = new BigDecimal("23452.4523434");
BigDecimal fracBd = bd.subtract(new BigDecimal(bd.toBigInteger()));

Further, you can try the abs() method to ensure the fraction part is positive:

BigDecimal fracBd = bd.subtract(new BigDecimal(bd.toBigInteger())).abs();



回答4:


This return "4523434" , even if you set the number in negative "-23452.4523434".

 BigDecimal d = BigDecimal.valueOf(23452.4523434);
 BigInteger decimal = d.remainder(BigDecimal.ONE).movePointRight(d.scale()).abs().toBigInteger();



回答5:


It doesn't work!!!

BigDecimal d = BigDecimal.valueOf(23452.4523434);
BigInteger decimal = 
d.remainder(BigDecimal.ONE).movePointRight(d.scale()).abs().toBigInteger();

When you input number, which fractional-part starts with '0', for ex. "123.00456". You get "456" instead of "00456". It happens because we convert it .toBigInteger(), and the first zeros just gone; If you use .toString() instead of .toBigInteger(), you get 456.00000, it's wrong too!

So my advise is using this:

BigDecimal fractPart = bd.remainder(BigDecimal.ONE);
StringBuilder sb = new StringBuilder(fractPart.toString());
sb.delete(0, 2);
String str = sb.toString();

And then just use this str how you want



来源:https://stackoverflow.com/questions/10038749/java-extract-just-the-fractional-part-of-a-bigdecimal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!