# Thread: Output a Two Decimal Value

1. Member
Join Date
Jul 2011
Posts
3
Rep Power
0

## Output a Two Decimal Value

It's suppose to display 12.50 but instead it's displaying 0.0

Java Code:
```import java.io.*;

public class InputOutput {
public static void main(String[] args) {
String base="";
String height="";

try {
System.out.print("Input base value = ");
System.out.print("Input height value = ");
} catch(IOException e) {
System.out.print("Error");
}

float area = 1/2*(Integer.parseInt(base)* Integer.parseInt(height));
System.out.println("The Area of the right triangle is "+ area);
}
}```

2. Integer division (as in 1/2) chops of the entire fractional part of the quotient, so 1/2 == 0. Either multiply by 0.5 or do the division using floating point numbers, as in 1.0/2.0

kind regards,

Jos

3. Member
Join Date
Jul 2011
Posts
3
Rep Power
0
But i need to use the formula 1/2*bh for computing for the area of the triangle. What should I change in the code?

4. Originally Posted by Hillsid3
But i need to use the formula 1/2*bh for computing for the area of the triangle. What should I change in the code?
0.5*bh?

kind regards,

Jos (<--- rocket scientist)

5. Member
Join Date
Jul 2011
Posts
3
Rep Power
0
no, i mean i still have to use 1/2 not 0.5

6. Originally Posted by Hillsid3
no, i mean i still have to use 1/2 not 0.5
Who said so? b.t.w. 1/2 equals 0 in Java, so you can't use it here, you have to rewrite your expression a bit ...

kind regards,

Jos

8. Member
Join Date
Jul 2011
Posts
1
Rep Power
0
Both of these will work:

float area = (1f/2f) * (Integer.parseInt(base)* Integer.parseInt(height));

float area = (0.5f) * (Integer.parseInt(base)* Integer.parseInt(height));

The problem is (as JosAH says) is that 1/2 =0.0 (because they are assumed to be int literals) so you need to make them float literals to return 0.5 correctly.

-Babbard

#### Posting Permissions

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