Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Fix incorrect result from casting double to decimal #12600

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 22 additions & 8 deletions velox/type/DecimalUtil.h
Original file line number Diff line number Diff line change
Expand Up @@ -258,17 +258,31 @@ class DecimalUtil {
// LONG_DOUBLE_MAX.
long double scaledValue = std::round(
(long double)value * DecimalUtil::kPowersOfTen[fractionDigits]);
if (scale > fractionDigits) {
scaledValue *= DecimalUtil::kPowersOfTen[scale - fractionDigits];
} else {
scaledValue /= DecimalUtil::kPowersOfTen[fractionDigits - scale];
}

const auto result = folly::tryTo<TOutput>(std::round(scaledValue));
const auto result = folly::tryTo<TOutput>(scaledValue);
if (result.hasError()) {
return Status::UserError("Result overflows.");
}
const TOutput rescaledValue = result.value();
TOutput rescaledValue = result.value();
if (scale > fractionDigits) {
bool isOverflow = __builtin_mul_overflow(
rescaledValue,
DecimalUtil::kPowersOfTen[scale - fractionDigits],
&rescaledValue);
if (isOverflow) {
return Status::UserError("Result overflows.");
}
} else if (fractionDigits > scale) {
const auto scalingFactor =
DecimalUtil::kPowersOfTen[fractionDigits - scale];
const TOutput remainder = rescaledValue % scalingFactor;
rescaledValue /= scalingFactor;
if (rescaledValue >= 0 && remainder >= scalingFactor / 2) {
++rescaledValue;
} else if (remainder <= -scalingFactor / 2) {
--rescaledValue;
}
}

if (!valueInPrecisionRange<TOutput>(rescaledValue, precision)) {
return Status::UserError(
"Result cannot fit in the given precision {}.", precision);
Expand Down
2 changes: 2 additions & 0 deletions velox/type/tests/DecimalTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,8 @@ TEST(DecimalTest, rescaleDouble) {
assertRescaleDouble(
10.03, DECIMAL(38, 18), HugeInt::parse("1003" + zeros(16)));
assertRescaleDouble(0.034567890, DECIMAL(38, 18), 34'567'890'000'000'000);
assertRescaleDouble(
0.03456789, DECIMAL(38, 33), HugeInt::parse("3456789" + zeros(25)));
assertRescaleDouble(
0.999999999999999, DECIMAL(38, 18), 999'999'999'999'999'000);
assertRescaleDouble(
Expand Down
Loading