Results 1 to 2 of 2

Thread: casting an int

  1. #1
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default casting an int

    I am trying to take numbers in as an int, then put out the decimal value. for example, 1/2 = 1.2. here is my code:

    Java Code:
          Scanner console = new Scanner(System.in);
    		System.out.print("numerator: ");
          int numerator = console.nextInt();
    
    		System.out.print("denominator: ");
          int denominator = console.nextInt();
    		
    		double fraction = (double) (numerator/denominator);
    Only problem is, i get 0. am i casting wrong?

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: casting an int

    Quote Originally Posted by droidus View Post
    I am trying to take numbers in as an int, then put out the decimal value. for example, 1/2 = 1.2. here is my code:

    Java Code:
          Scanner console = new Scanner(System.in);
    		System.out.print("numerator: ");
          int numerator = console.nextInt();
    
    		System.out.print("denominator: ");
          int denominator = console.nextInt();
    		
    		double fraction = (double) (numerator/denominator);
    Only problem is, i get 0. am i casting wrong?
    It's a matter of order. With your parenthesis as they are: (double) (numerator/denominator), you first do int division which always returns an int (here zero), and then change it to a double. Instead place the cast inside the parenthesis:

    Java Code:
    double fraction = ((double) numerator/denominator);

    In fact there's no need for the outer parenthesis at all:

    Java Code:
    double fraction = (double) numerator/denominator;

Similar Threads

  1. Casting int[][] to int[]
    By subith86 in forum New To Java
    Replies: 2
    Last Post: 02-02-2011, 10:48 AM
  2. Casting
    By zzpprk in forum Advanced Java
    Replies: 13
    Last Post: 08-13-2009, 07:59 PM
  3. What does casting mean?
    By sev51 in forum New To Java
    Replies: 3
    Last Post: 01-27-2009, 04:31 PM
  4. casting help
    By soc86 in forum New To Java
    Replies: 4
    Last Post: 01-13-2009, 11:07 PM
  5. Casting
    By leebee in forum New To Java
    Replies: 5
    Last Post: 08-10-2007, 12:24 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •