Sunday, January 1, 2012

Puzzle: Time for a change JAVA

Consider the following problem:
     Ram goes to the auto parts store to buy a spark plug that costs $1.10, but all he has in his wallet are two-dollar bills. How much change should he get if he pays for the spark plug with a two-dollar bill?

Here is a problem that attempts to solve the word problem. What does it print?

CODE:
public class Change
{
  public static void main(String args[])
  {
     System.out.println(2.00-1.10);
  }
}
Output:
0.8999999999999999

Here is a concept of BigDecimal :



BigDecimal performs exact decimal arithmetic. It also interoperates with the SQL DECIMAL type via JDBC. There is one caveat: Always use the BigDecimal(String) constructor, never BigDecimal(Double).The latter constructor creates an instance with the exact value of its argument: new BigDecimal(.1) returns a decimal representing  0.1000000000000000055511151231257827021181583404541015625.

Using BigDecimal correctly, the program prints the expected result of 0.90:


import java.math.BigDecimal;
public class Change
{
  public static void main(String args[])
  {
    System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.10")));
  }
}

Output:
0.90

//avoid float and double where exact answers are required use int,long  or BigDecimal.

Source:
Book: Java Puzzlers by JOSHUA BLOCH and NEAL GAFTER

No comments:

Post a Comment