/** * Converts this {@code BigDecimal} to a {@code long}, checking * for lost information. If this {@code BigDecimal} has a * nonzero fractional part or is out of the possible range for a * {@code long} result then an {@code ArithmeticException} is * thrown. * * @return this {@code BigDecimal} converted to a {@code long}. * @throws ArithmeticException if {@code this} has a nonzero * fractional part, or will not fit in a {@code long}. * @since 1.5 */ public long longValueExact() { if (intCompact != INFLATED && scale == 0) return intCompact; // If more than 19 digits in integer part it cannot possibly fit if ((precision() - scale) > 19) // [OK for negative scale too] throw new java.lang.ArithmeticException("Overflow"); // Fastpath zero and < 1.0 numbers (the latter can be very slow // to round if very small) if (this.signum() == 0) return 0; if ((this.precision() - this.scale) <= 0) throw new ArithmeticException("Rounding necessary"); // round to an integer, with Exception if decimal part non-0 BigDecimal num = this.setScale(0, ROUND_UNNECESSARY); if (num.precision() >= 19) // need to check carefully LongOverflow.check(num); return num.inflate().longValue(); }
/** * Converts this {@code BigDecimal} to a {@code long}, checking * for lost information. If this {@code BigDecimal} has a * nonzero fractional part or is out of the possible range for a * {@code long} result then an {@code ArithmeticException} is * thrown. * * @return this {@code BigDecimal} converted to a {@code long}. * @throws ArithmeticException if {@code this} has a nonzero * fractional part, or will not fit in a {@code long}. * @since 1.5 */ public long longValueExact() { if (intCompact != INFLATED && scale == 0) return intCompact; // If more than 19 digits in integer part it cannot possibly fit if ((precision() - scale) > 19) // [OK for negative scale too] throw new java.lang.ArithmeticException("Overflow"); // Fastpath zero and < 1.0 numbers (the latter can be very slow // to round if very small) if (this.signum() == 0) return 0; if ((this.precision() - this.scale) <= 0) throw new ArithmeticException("Rounding necessary"); // round to an integer, with Exception if decimal part non-0 BigDecimal num = this.setScale(0, ROUND_UNNECESSARY); if (num.precision() >= 19) // need to check carefully LongOverflow.check(num); return num.inflate().longValue(); }