Skip to content

Commit

Permalink
Change the logic to check scale and precision
Browse files Browse the repository at this point in the history
  • Loading branch information
KavinduZoysa committed Apr 8, 2022
1 parent 0a895dc commit 3f30ae2
Showing 1 changed file with 6 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,21 +53,14 @@ public static double round(double x, long fractionDigits) {
// Down cast can be done safely because of above condition.
int fractionDigitsAsInt = (int) fractionDigits;
BigDecimal xInBigDecimal = BigDecimal.valueOf(x);
BigDecimal xTmp = xInBigDecimal;
int digitsTmp = fractionDigitsAsInt;
if (digitsTmp > 0) {
while (digitsTmp-- > 0) {
if (xTmp.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO) == 0) {
return x;
}
xTmp = xTmp.multiply(BigDecimal.TEN);
int scale = xInBigDecimal.scale();
if (fractionDigitsAsInt > 0) {
if (fractionDigitsAsInt > scale) {
return x;
}
} else {
while (digitsTmp++ < 0) {
if (xTmp.compareTo(BigDecimal.ZERO) == 0) {
return 0;
}
xTmp = xTmp.divide(BigDecimal.TEN, 0, RoundingMode.DOWN);
if (-fractionDigitsAsInt > (xInBigDecimal.precision() - scale)) {
return 0;
}
}
return xInBigDecimal.setScale(fractionDigitsAsInt, RoundingMode.HALF_EVEN).doubleValue();
Expand Down

0 comments on commit 3f30ae2

Please sign in to comment.