简体   繁体   中英

Comparing BigDecimal and int in Java

哪一个是比较Java中BigDecimal和int的最佳方法:将BigDecimal转换为int或将int转换为BigDecimal?

If you expect the BigDecimal value to be really big (ie outside the range of int values, which is -2 31 to 2 31 -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.

Otherwise, if performance is a really big issue (which is rare), it might be better the other way around.

You want to convert the int to a 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的范围,因此无论如何都必须将int转换为BigDecimal以确保它们可以进行比较。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM