Skip to content

Commit ef6ad6c

Browse files
jprantekimchy
authored andcommitted
mapping BigDecimal to double or string in XContentBuilder
1 parent b5d9d3d commit ef6ad6c

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/main/java/org/elasticsearch/common/xcontent/XContentBuilder.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@
3636
import java.io.IOException;
3737
import java.io.InputStream;
3838
import java.io.OutputStream;
39+
import java.math.BigDecimal;
40+
import java.math.RoundingMode;
3941
import java.util.Date;
4042
import java.util.Map;
4143

@@ -470,6 +472,42 @@ public XContentBuilder field(XContentBuilderString name, double value) throws IO
470472
return this;
471473
}
472474

475+
public XContentBuilder field(String name, BigDecimal value) throws IOException {
476+
return field(name, value, value.scale(), RoundingMode.HALF_UP, true);
477+
}
478+
479+
public XContentBuilder field(XContentBuilderString name, BigDecimal value) throws IOException {
480+
return field(name, value, value.scale(), RoundingMode.HALF_UP, true);
481+
}
482+
483+
public XContentBuilder field(String name, BigDecimal value, int scale, RoundingMode rounding, boolean toDouble) throws IOException {
484+
field(name);
485+
if (toDouble) {
486+
try {
487+
generator.writeNumber(value.setScale(scale, rounding).doubleValue());
488+
} catch (ArithmeticException e) {
489+
generator.writeString(value.toEngineeringString());
490+
}
491+
} else {
492+
generator.writeString(value.toEngineeringString());
493+
}
494+
return this;
495+
}
496+
497+
public XContentBuilder field(XContentBuilderString name, BigDecimal value, int scale, RoundingMode rounding, boolean toDouble) throws IOException {
498+
field(name);
499+
if (toDouble) {
500+
try {
501+
generator.writeNumber(value.setScale(scale, rounding).doubleValue());
502+
} catch (ArithmeticException e) {
503+
generator.writeString(value.toEngineeringString());
504+
}
505+
} else {
506+
generator.writeString(value.toEngineeringString());
507+
}
508+
return this;
509+
}
510+
473511
public XContentBuilder field(String name, BytesReference value) throws IOException {
474512
field(name);
475513
if (!value.hasArray()) {

0 commit comments

Comments
 (0)