# how to calculate division in java

• 03-26-2012, 02:05 PM
noobplus
how to calculate division in java
hi,

Code:

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

how to make it 0.5?

regards
dhilip
• 03-26-2012, 02:16 PM
KevinWorkman
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).
• 03-26-2012, 02:18 PM
gauravfzd
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
• 03-26-2012, 02:19 PM
noobplus
Re: how to calculate division in java
Quote:

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).

Code:

```double a=(double)1/(double)2; System.out.println(a);```
the output was 0.5

thank you very much
dhilip
• 03-26-2012, 02:20 PM
noobplus
Re: how to calculate division in java
Quote:

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

Code:

`double a=1d/2d;`
gave me output 0.5

thank you very much

dhilip
• 09-07-2016, 08:51 AM
prakashsanjay
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
• 09-07-2016, 11:27 AM
SurfMan
Re: how to calculate division in java
Quote:

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 :)