Using double variable for storing 2.9 value gives different result

In our code we are using double everywhere basically when we receive this value from json response or sending this value back again its in double datatype

The issue we found is when we assign 2.9 value to a double variable. It assigns it as 2.899999 and this is the value which is being in used in amount calculation everywhere. Due this sometimes it throws a cent off

Any idea how to solve this and whats the best practice generally being used in the industry ?

That is the usual problem with Double or Float when represented as Decimals. 2.89999999 is the same number as 2.9

Several ways to solve:

  • use formatter to present in String
  • Use Decimal type

In anycase, take care when comparing 2 doubles of this precision constraints.

Using double variable for storing 2.9 value gives different result
 
 
Q