0

I have a table on a jsp which displays data from an mysql table. One column shows the product of the multiplication of two floats from the db. This is the code for the calculation of that field:

<td><%=rs.getFloat("price")* rs.getFloat("available")%></td>

The problem is if for example price = 16.90 and available = 144 then the result = 2433.5999. Why does it not give 2433.6? How can I get 2433.6

Alfie Danger
  • 377
  • 5
  • 23
  • 3
    Go through this https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate – Trishul Singh Choudhary Feb 22 '20 at 10:07
  • I understand why it is happening now just not sure how I can avoid it? – Alfie Danger Feb 22 '20 at 10:24
  • 1
    By not using float, but a fixed point type (`BigDecimal` in Java, and `NUMERIC` or `DECIMAL` in the database). Also, even if you using floating point numbers in Java, usually you should prefer the 64 bit `double` over the 32 bit `float`. – Mark Rotteveel Feb 22 '20 at 11:00
  • ok nice thank you! I used double but still got some weird results (less than before but still a few). How can I use BigDecimal? rs.getBigDecimal("price") gives me an error – Alfie Danger Feb 22 '20 at 21:33
  • I want to always get the number to two decimal places. I am already using DECIMAL on the database side. Do both need to be decimals? i.e. both price and available – Alfie Danger Feb 22 '20 at 21:43
  • I managed to get what I want by editing my code to: (rs.getBigDecimal("price")).multiply(rs.getBigDecimal("available")) – Alfie Danger Feb 23 '20 at 00:48

0 Answers0