Skip to content

Commit 161fbf3

Browse files
committed
Apply MathContext on BigDecimal creation where possible (and necessary)
This avoids creation of objects in subsequent rounding step
1 parent 3bfd4d5 commit 161fbf3

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

src/main/java/org/firebirdsql/decimal/Decimal.java

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323

2424
import java.math.BigDecimal;
2525
import java.math.BigInteger;
26+
import java.math.MathContext;
2627

2728
import static java.util.Objects.requireNonNull;
2829

@@ -282,6 +283,13 @@ public final DecimalFormat getDecimalFormat() {
282283
return decimalFormat;
283284
}
284285

286+
/**
287+
* @return Math context for the decimal type constructed.
288+
*/
289+
private MathContext getMathContext() {
290+
return decimalFormat.getMathContext();
291+
}
292+
285293
/**
286294
* @see DecimalFormat#validate(BigDecimal)
287295
*/
@@ -332,7 +340,7 @@ final T valueOf(BigDecimal value, OverflowHandling overflowHandling) {
332340
* @see #valueOfExact(BigInteger)
333341
*/
334342
final T valueOf(BigInteger value, OverflowHandling overflowHandling) {
335-
return valueOf(new BigDecimal(value), overflowHandling);
343+
return valueOf(new BigDecimal(value, getMathContext()), overflowHandling);
336344
}
337345

338346
/**
@@ -375,7 +383,8 @@ final T valueOf(double value, OverflowHandling overflowHandling) {
375383
return getSpecialConstant(Signum.NEGATIVE, DecimalType.INFINITY);
376384
}
377385

378-
return valueOf(BigDecimal.valueOf(value), overflowHandling);
386+
// TODO Use new BigDecimal(double, MathContext) instead, has slightly different precision?
387+
return valueOf(new BigDecimal(Double.toString(value), getMathContext()), overflowHandling);
379388
}
380389

381390
/**
@@ -436,7 +445,7 @@ final T valueOf(String value, OverflowHandling overflowHandling) {
436445
return valueOfSpecial(value);
437446
}
438447
}
439-
BigDecimal bdValue = new BigDecimal(value);
448+
BigDecimal bdValue = new BigDecimal(value, getMathContext());
440449
T decimalValue = valueOf(bdValue, overflowHandling);
441450
if (decimalValue.isEquivalentToZero()
442451
&& value.charAt(0) == '-'

0 commit comments

Comments
 (0)