Search in sources :

Example 1 with Decimal128

use of de.undercouch.bson4jackson.types.Decimal128 in project bson4jackson by michel-kraemer.

the class BsonGeneratorTest method writeBigDecimalsAsDecimal128s.

/**
 * Test if {@link BigDecimal} objects can be serialized as {@link Decimal128}s
 * @throws Exception if something goes wrong
 */
@Test
public void writeBigDecimalsAsDecimal128s() throws Exception {
    Map<String, Object> data = new LinkedHashMap<String, Object>();
    data.put("big", new BigDecimal("0.3"));
    BSONObject obj = generateAndParse(data);
    Double result = (Double) obj.get("big");
    // BigDecimal("0.3") does not equal 0.3!
    assertEquals(0.3, result, 0.000001);
    assertFalse(Double.valueOf(0.3).equals(result));
    data = new LinkedHashMap<String, Object>();
    data.put("big", new BigDecimal("0.3"));
    obj = generateAndParse(data, Feature.WRITE_BIGDECIMALS_AS_DECIMAL128);
    org.bson.types.Decimal128 strResult = (org.bson.types.Decimal128) obj.get("big");
    assertEquals(new BigDecimal("0.3"), strResult.bigDecimalValue());
}
Also used : BSONObject(org.bson.BSONObject) SerializableString(com.fasterxml.jackson.core.SerializableString) SerializedString(com.fasterxml.jackson.core.io.SerializedString) Decimal128(de.undercouch.bson4jackson.types.Decimal128) BigDecimal(java.math.BigDecimal) LinkedHashMap(java.util.LinkedHashMap) BSONObject(org.bson.BSONObject) Test(org.junit.Test)

Example 2 with Decimal128

use of de.undercouch.bson4jackson.types.Decimal128 in project bson4jackson by michel-kraemer.

the class BsonGenerator method writeNumber.

@Override
public void writeNumber(BigDecimal dec) throws IOException, JsonGenerationException {
    if (isEnabled(Feature.WRITE_BIGDECIMALS_AS_DECIMAL128)) {
        Decimal128 d = new Decimal128(dec);
        _writeArrayFieldNameIfNeeded();
        _verifyValueWrite("write number");
        _buffer.putByte(_typeMarker, BsonConstants.TYPE_DECIMAL128);
        _buffer.putLong(d.getLow());
        _buffer.putLong(d.getHigh());
        flushBuffer();
        return;
    }
    if (isEnabled(Feature.WRITE_BIGDECIMALS_AS_STRINGS)) {
        writeString(dec.toString());
        return;
    }
    float f = dec.floatValue();
    if (!Float.isInfinite(f)) {
        writeNumber(f);
    } else {
        double d = dec.doubleValue();
        if (!Double.isInfinite(d)) {
            writeNumber(d);
        } else {
            writeString(dec.toString());
        }
    }
}
Also used : Decimal128(de.undercouch.bson4jackson.types.Decimal128)

Aggregations

Decimal128 (de.undercouch.bson4jackson.types.Decimal128)2 SerializableString (com.fasterxml.jackson.core.SerializableString)1 SerializedString (com.fasterxml.jackson.core.io.SerializedString)1 BigDecimal (java.math.BigDecimal)1 LinkedHashMap (java.util.LinkedHashMap)1 BSONObject (org.bson.BSONObject)1 Test (org.junit.Test)1