| 489 | })(); |
| 490 | |
| 491 | BasicDecimal128 FromDouble(double in, int32_t precision, int32_t scale, bool* overflow) { |
| 492 | // Multiply decimal with the scale |
| 493 | auto unscaled = in * kDoubleScaleMultipliers[scale]; |
| 494 | DECIMAL_OVERFLOW_IF(std::isnan(unscaled), overflow); |
| 495 | |
| 496 | unscaled = std::round(unscaled); |
| 497 | |
| 498 | // convert scaled double to int128 |
| 499 | int32_t sign = unscaled < 0 ? -1 : 1; |
| 500 | auto unscaled_abs = std::abs(unscaled); |
| 501 | |
| 502 | // overflow if > 2^127 - 1 |
| 503 | DECIMAL_OVERFLOW_IF(unscaled_abs > std::ldexp(static_cast<double>(1), 127) - 1, |
| 504 | overflow); |
| 505 | |
| 506 | uint64_t high_bits = static_cast<uint64_t>(std::ldexp(unscaled_abs, -64)); |
| 507 | uint64_t low_bits = static_cast<uint64_t>( |
| 508 | unscaled_abs - std::ldexp(static_cast<double>(high_bits), 64)); |
| 509 | |
| 510 | auto result = BasicDecimal128(static_cast<int64_t>(high_bits), low_bits); |
| 511 | |
| 512 | // overflow if > max value based on precision |
| 513 | DECIMAL_OVERFLOW_IF(result > GetMaxValue(precision), overflow); |
| 514 | return result * sign; |
| 515 | } |
| 516 | |
| 517 | double ToDouble(const BasicDecimalScalar128& in, bool* overflow) { |
| 518 | // convert int128 to double |