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

[GH-3146] Optimize the binaryToDecimal function #3147

Closed
wants to merge 1 commit into from
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@

package org.apache.parquet.pig.convert;

import static java.lang.Math.pow;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
Expand Down Expand Up @@ -53,11 +51,7 @@ public static BigDecimal binaryToDecimal(Binary value, int precision, int scale)
}
int bits = 8 * (end - start);
long unscaledNew = (unscaled << (64 - bits)) >> (64 - bits);
if (unscaledNew <= -pow(10, 18) || unscaledNew >= pow(10, 18)) {
return new BigDecimal(unscaledNew);
} else {
return BigDecimal.valueOf(unscaledNew / pow(10, scale));
}
return BigDecimal.valueOf(unscaledNew, scale);
} else {
return new BigDecimal(new BigInteger(value.getBytes()), scale);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,12 @@ public void testBinaryToDecimal() throws Exception {
// Test LONG
testDecimalConversion(Long.MAX_VALUE, 19, 0, "9223372036854775807");
testDecimalConversion(Long.MIN_VALUE, 19, 0, "-9223372036854775808");
testDecimalConversion(0L, 0, 0, "0.0");
testDecimalConversion(0L, 0, 0, "0");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do these two lines need change?

Copy link
Author

@qian0817 qian0817 Feb 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For this use case, 0 is the correct value. Using double to construct BigDecimal previously may lead to potential incorrect behavior.


// Test INTEGER
testDecimalConversion(Integer.MAX_VALUE, 10, 0, "2147483647");
testDecimalConversion(Integer.MIN_VALUE, 10, 0, "-2147483648");
testDecimalConversion(0, 0, 0, "0.0");
testDecimalConversion(0, 0, 0, "0");

// Test DOUBLE
testDecimalConversion(12345678912345678d, 17, 0, "12345678912345678");
Expand Down