-3

my program is receiving amount value as string and then converting it to Double using Double.parseDouble(transAmt).

Now we are getting issue when amount passed is "100.00" .

Please advise if while casting to double zero precision digits will be lost

Ravinder Reddy
  • 23,692
  • 6
  • 52
  • 82
Prerna S
  • 1
  • 1

2 Answers2

1

With some guessing what the "issue" might be: double in Java is an approximation of the mathematical real numbers. As such there is no difference between 100 and 100.00 it is just the same value.

Henry
  • 42,982
  • 7
  • 68
  • 84
0

double holds no precision, and is an approximation, a sum of (negative) powers of 2. Hence 3.10 might on output be 3.0999999785, an error which enlarges when summing or multiplying.

For holding a precision and being precise - as with financial software - BigDecimal is used.

BigDecimal amount = new BigDecimal("12.99"); // A precision of 2 digits.
BigDecimal base = new BigDecimal("4.33");
assert base.multiply(BigDecimal.valueOf(3)).compareTo(amount) == 0;

Unfortunately with BigDecimal normal math operators are not available, but in general it is not as unsafe as with double.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138