0

I'm using Google App Engine for Java with Objectify 4.0b1 to persist a POJO into the Datastore. That POJO has a few Float properties. If I set one of them to a Float equal to 51.5221, save it, then look in to console at that entity, the value has become 51.522098541259766. Why?

The 51.5221 value has come from parsing a String using Float.valueOf(), in case that makes any difference.

I expect some people will tell me to use BigDecimal if I want control of the precision. Fine, but where is the extra data coming from? Is it strictly necessary to use BigDecimal or store Integers and convert back to Floats later? I'd like to avoid both.

Dan McGrath
  • 41,220
  • 11
  • 99
  • 130
Eliot
  • 2,349
  • 3
  • 28
  • 45
  • The internal representation of `51.5221` has some variance to it due to the inability to represent it *exactly* in the internal binary floating point format. So when you display it or save it, you are getting the actual rendering of the internal binary. (*e.g.*, see http://msdn.microsoft.com/en-us/library/c151dt3s.aspx or http://stackoverflow.com/questions/9364399/storing-floating-point-numbers-in-android-database) That's why BigDecimal was invented. – lurker Apr 16 '14 at 11:21
  • I suggest you read this http://stackoverflow.com/questions/588004/is-floating-point-math-broken when dealing with floats it's important to understand what is actually going on, other wise you will get caught out with this sort of behaviour. – Tim Hoffman Apr 17 '14 at 11:55

0 Answers0