This discussion is archived
2 Replies Latest reply: Jun 7, 2013 9:01 PM by rp0428 RSS

Type Casting

Omariot Newbie
Currently Being Moderated
So I am attending a class and we are learning about "Type Casting" and the book gives the example below. From my only comment in the code, I am confused about how the program is giving me two decimal places.

So the question is "How am I getting a number with two decimal places as output?"

-----
import java.util.Scanner;

public class SalesTax
{

public static void main(String[] args)
{
double purchase, tax;
Scanner input = new Scanner(System.in);

System.out.print("Enter purchase amount: ");
purchase = input.nextDouble();
tax = purchase * 0.06;
System.out.println("Sales Tax: $" + (int)(tax * 100) / 100.0); +//this will give two decimal places??+
}

}
  • 1. Re: Type Casting
    EJP Guru
    Currently Being Moderated
    The (int) typecast only applies to the following primary-expression, which is (tax*100). The int-valued result is then divided by 100.0, which yields a double-valued result. If you pass that to an appropriate formatter you will see the number of decimal places specified in the formatter.

    Note that the decimal places aren't in the double value itself: doubles have binary places, not decimal places. In this case System.out.println() is the formatter, and whatever it does internally happens to yield 2 decimal places. I wouldn't rely on it personally, I would use a BigDecimal or a DecimalFormatter.
  • 2. Re: Type Casting
    rp0428 Guru
    Currently Being Moderated
    Welcome to the forum!
    >
    So I am attending a class and we are learning about "Type Casting" and the book gives the example below. From my only comment in the code, I am confused about how the program is giving me two decimal places.

    So the question is "How am I getting a number with two decimal places as output?"
    >
    Since you are learning about "Type Casting" read EJPs reply and then instead of
    System.out.println("Sales Tax: $" + (int)(tax * 100) / 100.0); //this will give two decimal places??
    Try this and see what you get
    System.out.println("Sales Tax: $" + (int)((tax * 100) / 100.0)); //this will give two decimal places??
    Cast the result of the entire computation to an 'int'.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points