比较 Java 中的 BigDecimal 和 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9759975/
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
Comparing BigDecimal and int in Java
提问by HighBit
Which one is the best way of comparing a BigDecimal and an int in Java : coverting the BigDecimal to int or converting int to BigDecimal ?
在 Java 中比较 BigDecimal 和 int 的最佳方法是哪一种:将 BigDecimal 转换为 int 或将 int 转换为 BigDecimal?
采纳答案by Péter T?r?k
If you expect the BigDecimal
value to be really big (i.e. outside the range of int
values, which is -231to 231-1) and/or to contain decimal digits, or simply want to play safe, you should convert the int
to BigDecimal
to avoid overflow / truncation errors.
如果你期待BigDecimal
值是非常大的(即范围以外的int
值,这是-2 31到2 31-1)和/或包含十进制数字,或只是想为了稳妥起见,你应该转换int
到BigDecimal
以避免溢出/截断错误。
Otherwise, if performance is a really big issue (which is rare), it mightbe better the other way around.
否则,如果性能是一个非常大的问题(这种情况很少见),那么反过来可能会更好。
回答by Bober02
One reason not to convert int to BigDecimal is the fact that you would be creating a new object, therefore you are really throwing garbage on your heap to perform equality. Also, primitive equality would be faster than the one on the actual BigInteger object as well.
不将 int 转换为 BigDecimal 的一个原因是您将创建一个新对象,因此您实际上是在堆上扔垃圾以执行相等。此外,原始相等也会比实际 BigInteger 对象上的相等更快。
回答by Taymon
You want to convert the int
to a BigDecimal
.
您想将 转换int
为BigDecimal
.
This is because you won't always be able to convert a BigDecimal to an int; you'll lose any information after the decimal point and the value of the BigDecimal might be outside the range of an int.
这是因为您并不总是能够将 BigDecimal 转换为 int;您将丢失小数点后的任何信息,并且 BigDecimal 的值可能超出 int 的范围。
回答by Sirko
As BigDecimal
extends the range of int
you will have to convert the int
into BigDecimal
to be sure they can be compared, anyhow.
随着BigDecimal
范围的扩大,int
您必须将 转换int
为BigDecimal
以确保它们可以进行比较,无论如何。