BigDecimalConverter issue

902 views
Skip to first unread message

שי גבעתי

unread,
Oct 31, 2017, 10:59:36 AM10/31/17
to Morphia
I'm breaking my head over this issue for more than a day without a solution. 
I'm using mongo-java-driver-3.5.0.jar with morphia-1.3.2.jar.
I have a POJO with a BigDecimal field, that I try to persist to db, using the following code: 

        morphia = new Morphia();
        morphia.mapPackage("objects.mongo");
        morphia.getMapper().getConverters().addConverter(new BigDecimalConverter());
        datastore = morphia.createDatastore(new MongoClient(), "myDb");
        datastore.ensureIndexes();
        MyClass myClass= new MyClass();
        myClass.setBigDecimal(new BigDecimal(1.11111111111111111111111111111));
        datastore.save(myClass);



But I get the following exception: 
Caused by: java.lang.RuntimeException: java.lang.NumberFormatException: Conversion to Decimal128 would require inexact rounding of 1.111111111111111160454356650006957352161407470703125
at org.mongodb.morphia.mapping.ValueMapper.toDBObject(ValueMapper.java:29)
at org.mongodb.morphia.mapping.Mapper.writeMappedField(Mapper.java:867)
at org.mongodb.morphia.mapping.Mapper.toDBObject(Mapper.java:982)
... 7 more
Caused by: java.lang.NumberFormatException: Conversion to Decimal128 would require inexact rounding of 1.111111111111111160454356650006957352161407470703125
at org.bson.types.Decimal128.ensureExactRounding(Decimal128.java:244)
at org.bson.types.Decimal128.clampAndRound(Decimal128.java:233)
at org.bson.types.Decimal128.<init>(Decimal128.java:169)
at org.bson.types.Decimal128.<init>(Decimal128.java:156)
at org.mongodb.morphia.converters.BigDecimalConverter.encode(BigDecimalConverter.java:81)
at org.mongodb.morphia.converters.Converters.toDBObject(Converters.java:232)
at org.mongodb.morphia.mapping.ValueMapper.toDBObject(ValueMapper.java:27)
... 9 more
I can't figure out what am I missing here?
All help would be appreciated

capta...@gmail.com

unread,
Aug 17, 2018, 6:09:32 PM8/17/18
to Morphia
The Decimal128 type only supports up to 34 digits of precision.  (Generally, "precision" = total # of digits, while "scale" = # of decimal digits).   Whereas a Java BigDecimal can go higher.  So, before saving to the DB, you need to round the BigDecimal value (e.g. use BigDecimal.setScale()) method. 
Reply all
Reply to author
Forward
0 new messages