Java 计算 bigdecimals 的百分比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2109860/
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
Compute percentage for bigdecimals
提问by Lluis Martinez
I haven't found any native method to do this, so I created my own in a helper class:
我还没有找到任何本地方法来做到这一点,所以我在帮助类中创建了自己的方法:
public static BigDecimal percentage(BigDecimal base, BigDecimal pct){
return base.multiply(pct).divide(new BigDecimal(100));
}
But I don't quite like it, I wonder if the API has something similar. The Number class (ancestor of BigDecimal) would be a nice place.
不过我不是很喜欢,不知道API有没有类似的东西。Number 类(BigDecimal 的祖先)将是一个不错的地方。
采纳答案by Michael Borgwardt
Feel free to subclass BigDecimal
and add that method. Beyond that, what do you expect? You know where to find the API and confirm that the class you would like to have that method doesn't. Personally, I'd say the functionality is so trivial that there wouldn't be much of a point in having it in the standard API.
随意子类化BigDecimal
并添加该方法。除此之外,你还有什么期待?您知道在哪里可以找到 API 并确认您希望使用该方法的类没有。就我个人而言,我会说该功能是如此微不足道,以至于在标准 API 中使用它没有多大意义。
回答by user85421
I don't think there is an API for that (I never needed it).
Your solution seams good to me, maybe you just add the constant ONE_HUNDRED
:
我不认为有一个 API(我从不需要它)。
您的解决方案对我来说很好,也许您只需添加常量ONE_HUNDRED
:
public static final BigDecimal ONE_HUNDRED = new BigDecimal(100);
public static BigDecimal percentage(BigDecimal base, BigDecimal pct){
return base.multiply(pct).divide(ONE_HUNDRED);
}
probably not that much gain, only if calledvery often
可能不是多大的收获,只有所谓的非常频繁
eventually put it in some Util class...
最终把它放在一些 Util 类中......
回答by trashgod
See also DecimalFormat. You can use the parent's factory method NumberFormat.getPercentInstance()
as shown here, hereet al.
另请参阅DecimalFormat。您可以使用父母的工厂方法NumberFormat.getPercentInstance()
如图所示在这里,在这里等人。
回答by Valentyn Danylchuk
You may want to implement the division by 100 using BigDecimal.scaleByPowerOfTen(-2)
.
您可能希望使用 100 实现除法BigDecimal.scaleByPowerOfTen(-2)
。
It adds up if you do it a million times. It is much faster in my experience.
如果你这样做一百万次,它就会加起来。根据我的经验,它要快得多。
There is also a similar method BigDecimal.movePointLeft(2)
- see the other threadfor details and decide which one works better for you.
还有一种类似的方法BigDecimal.movePointLeft(2)
-有关详细信息,请参阅另一个线程并确定哪种方法更适合您。