java 在 BigDecimal 中提取数字十进制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10383392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:47:51  来源:igfitidea点击:

Extract number decimal in BigDecimal

javabigdecimal

提问by Mehdi

How to extract a number after the decimal point using BigDecimal ?

如何使用 BigDecimal 提取小数点后的数字?

BigDecimal d = BigDecimal.valueOf(1548.5649);

BigDecimal d = BigDecimal.valueOf(1548.5649);

result : extract only : 5649

结果:仅提取:5649

回答by dogbane

Try:

尝试:

BigDecimal d = BigDecimal.valueOf(1548.5649);
BigDecimal result = d.subtract(d.setScale(0, RoundingMode.FLOOR)).movePointRight(d.scale());      
System.out.println(result);

prints:

印刷:

5649

回答by Mikita Belahlazau

Try BigDecimal.remainder:

尝试BigDecimal.remainder

BigDecimal d = BigDecimal.valueOf(1548.5649); 
BigDecimal fraction = d.remainder(BigDecimal.ONE);
System.out.println(fraction);
// Outputs 0.5649

回答by Matt McHenry

This should do the trick:

这应该可以解决问题:

d.subtract(d.setScale(0, RoundingMode.FLOOR));

setScale()rounds the number to zero decimal places, and despite its name, does not mutate the value of d.

setScale()将数字四舍五入到零个小数位,尽管它的名字,不会改变 的值d

回答by IvanRF

If the value is negative, using d.subtract(d.setScale(0, RoundingMode.FLOOR))will return a wrong decimal.

如果值为负,则 usingd.subtract(d.setScale(0, RoundingMode.FLOOR))将返回错误的小数。

Use this:

使用这个

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

It returns 5649for 1548.5649or -1548.5649

它返回56491548.5649-1548.5649

回答by JB Nizet

You don't tell which type you want as a result. The easiest way is probably to transform the BigDecimal into a String, and take a substring:

结果你不知道你想要哪种类型。最简单的方法可能是将 BigDecimal 转换为 String,并取一个子字符串:

String s = d.toPlainString();
int i = s.indexOf('.');
if (i < 0) {
    return "";
}
return s.substring(i + 1);

回答by user1335794

try to use d.doubleValue()to get the double value

尝试使用d.doubleValue()来获取双精度值