gpt4 book ai didi

Java BigDecimal 数据转换为相反符号长整型

转载 作者:行者123 更新时间:2023-12-01 07:50:02 24 4
gpt4 key购买 nike

根据Java 7 documentationjava.math.BigDecimal类中的方法longValue可以返回符号相反的结果。

Converts this BigDecimal to a long. This conversion is analogous to the narrowing primitive conversion from double to short as defined in section 5.1.3 of The Java™ Language Specification: any fractional part of this BigDecimal will be discarded, and if the resulting "BigInteger" is too big to fit in a long, only the low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this BigDecimal value as well as return a result with the opposite sign.

什么情况下可以?

最佳答案

只要 BigDecimal 的值大于 long 所能容纳的值,就有可能发生这种情况。

示例:

BigDecimal num = new BigDecimal(Long.MAX_VALUE);
System.out.println(num); // prints: 9223372036854775807
System.out.println(num.longValue()); // prints: 9223372036854775807

num = num.add(BigDecimal.TEN); // num is now too large for long
System.out.println(num); // prints: 9223372036854775817
System.out.println(num.longValue()); // prints: -9223372036854775799
System.out.println(num.longValueExact()); // throws: ArithmeticException: Overflow

关于Java BigDecimal 数据转换为相反符号长整型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39457844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com