3

I have a precision problem storing a float value in mysql via jpa (EclipseLink). In my code I have annotated the field with

@Column(precision=15, scale=7)
private float x;

But when i store a value like 322,249878 the database returns 322.25. Whats going on there :)?

Hans Sperker
  • 1,347
  • 2
  • 15
  • 37

1 Answers1

7

precision and scale settings are only applicable to exact numeric types (i.e. BigDecimal in Java and decimal in MySQL).

Floating point types (float and double) are approximate by their nature, therefore these settings don't make sense for them.

Also note that if you change type of this field to BigDecimal you should initialize it with precise values as well.

Community
  • 1
  • 1
axtavt
  • 239,438
  • 41
  • 511
  • 482
  • Ok thanks for that hint but it doesn't change anything for the precision ;-) – Hans Sperker Jun 19 '12 at 15:17
  • @jstr: Recheck it. Java type should be `BigDecimal`, MySQL type should be `decimal(15, 7)` (Hibernate will generate it from this annotation if you use schema generation), and field should be initialized by precise value. – axtavt Jun 19 '12 at 15:20
  • @jstr: Oh, it's EclipseLink, perhaps it behaves differently somehow. – axtavt Jun 19 '12 at 15:22
  • Ok so now I use BigDecimal which I initialize with Float.toString(x)) and with mit annotation @Column(precision=15, scale=7) the precision is preserved... works for me – Hans Sperker Jun 19 '12 at 15:45