0

I am trying to save a float value using hibernate into MS SQL Server. the value is 2.4 and when it get saved to the database, it becomes like this.

2.40000009536743

Here is the column definition in my entity class for this field.

@Column(name = "fTotalChipWeight")
    private float totalChipWeight;

Could anybody advise me why this is happening this way

This is how the database column is defined

enter image description here

KItis
  • 5,476
  • 19
  • 64
  • 112
  • 2.4 is not exactly representable in binary floating point, and type `float` only offers 6-7 decimal digits of precision. See [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). I hesitate to close this as a dupe only because there are some possible complexities related to the database column type and how and where the value is displayed, which have not been disclosed. – John Bollinger Dec 20 '18 at 04:05
  • I have modified the question with more details on the db column definition – KItis Dec 20 '18 at 04:16
  • An SQL `float` cannot represent 2.4. If you need exactly 2.4, using `decimal` might work. But we still do not have enough context to know what your situation is. – Eric Postpischil Dec 20 '18 at 04:21
  • You can try to change your database field to `numeric(6,2)` and for your entity use the `BigDecimal` instead. Could this help? – W-S Dec 20 '18 at 04:24
  • Also consider using `double`. Although the value as `double` is still inaccurate, it has twice the precision, and floating point errors are usually not visible to humans at the `double` precision. – SOFe Dec 20 '18 at 08:26
  • Although the question is still a little light on context and intent, I am persuaded that it is substantially a misunderstanding of floating point, which is addressed very well by the dupe target. To be clear, then: nothing is wrong. The computer and database are already storing and rertrieving the representable `float` value closest to 2.4. – John Bollinger Dec 20 '18 at 13:12

1 Answers1

0

When IEEE basic 32-bit binary floating-point format is used, 2.4 is not exactly representable. The nearest representable value is 2.400000095367431640625. When 2.4 is converted to 32-bit floating-point, that is the result. So you are seeing the actual value.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • could you advise me how to get it done so that I am able to save value 2.4. Which data type would allow to just save 2.4 as it is – KItis Dec 20 '18 at 04:12
  • 1
    @KItis: You have not shown us much context. You tagged the question with Java. If you put 2.4 into a `float`, then the value is 2.400000095367431640625, and the original 2.4 is gone. For the software to know 2.4 is intended, there must be more information than just a `float`. You have to supply more information about what you are doing. – Eric Postpischil Dec 20 '18 at 04:18