# Thread: how to calculate division in java

1. ## how to calculate division in java

hi,

Java Code:
```double a=1/2;
System.out.println(a);```
it gives me output 0

how to make it 0.5?

regards
dhilip  Reply With Quote

2. ## Re: how to calculate division in java

1 and 2 are both ints. An int divided by an int will give you an int. Variables that are ints do not have decimal places.

You can cast one or both of the values to a double before doing the division, or you could use double literals (1.0 instead of 1, for example).  Reply With Quote

3. ## Re: how to calculate division in java

in your code you are doing a integer division and then automatic type promotion is performed.So u will always get 1/2 as 0.
Use it like this:
float a = 1f; float b = 2f;
float c = a/b;

*you can use double instead of float  Reply With Quote

4. ## Re: how to calculate division in java Originally Posted by KevinWorkman 1 and 2 are both ints. An int divided by an int will give you an int. Variables that are ints do not have decimal places.

You can cast one or both of the values to a double before doing the division, or you could use double literals (1.0 instead of 1, for example).
Java Code:
```double a=(double)1/(double)2;
System.out.println(a);```
the output was 0.5

thank you very much
dhilip  Reply With Quote

5. ## Re: how to calculate division in java Originally Posted by gauravfzd in your code you are doing a integer division and then automatic type promotion is performed.So u will always get 1/2 as 0.
Use it like this:
float a = 1f; float b = 2f;
float c = a/b;

*you can use double instead of float
Java Code:
`double a=1d/2d;`
gave me output 0.5

thank you very much

dhilip  Reply With Quote

6. Member Join Date
Sep 2016
Posts
1
Rep Power
0

## Re: how to calculate division in java

package com.corejava.sonu;

import java.util.Scanner;

public class Division {

public static void main(String args[]){

float x,y,z;

System.out.println("Enter the two integers value");

Scanner in =new Scanner(System.in);

x=in.nextInt();
y=in.nextInt();
z=x/y;

System.out.println("Division of two integers="+z);

}

}

**try this simple example for division using float  Reply With Quote

7. ## Re: how to calculate division in java Originally Posted by prakashsanjay package com.corejava.sonu;
<snip>

**try this simple example for division using float
If noobplus (the OP) hasn't figured this out during the 4,5 years that have passed since this post, I'm pretty sure he will have given up on Java programming by now. At least he should, if he's still working on it :)  Reply With Quote

#### Posting Permissions

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