0
How can i get (22.22) as a output. I tried using double data type but I'm getting 22.0 Can anyone tell me the reason ?
8 ответов
+ 3
imabhiiiiii🥱 You're first doing integer division then implicitly casting the result to double that's why the output is 11.0
(Also as per Java naming convention only class names starts with capital letters)
As Simba pointed out you can either change the parameters type to double or you can just divide by 3.0 both will give you the same answer 11.6666666666
If you want to format the output to 2 decimal places then Java has quite a few ways.
Here is a site that teaches how to format decimals in 7 different ways.
Choose as per your need.
https://java2blog.com/format-double-to-2-decimal-places-java/
+ 5
Here, you defined your return type as double not parameters(numbers) that you used to calculate the average.
double Number1, double Number2....
+ 3
It should print as you expected.
double x = 2222;
double y = 100;
System.out.println(x/y);
How did you do that?
+ 2
class Calculator {
public double findAverage(int Number1,int Number2,int Number3){
double avg=(Number1+Number2+Number3)/3; //(35/3)
return avg;
}
}
class Tester {
public static void main(String args[]) {
Calculator calculator = new Calculator();
System.out.println(calculator.findAverage(12,8,15)); //35
//expected output is 11.67
}
}
+ 2
11.6666666666
but i want 11.66 🙂by the way thanks you
+ 1
Actually i have done this case but when it comes to (23.65). I'm getting 23.0
+ 1
Thank you Hazel i got my answer now
+ 1
Here, you define your return type as double not parameters that you used to the average.
answer 11.66666
here is a useful link for you :
https://java2blog.com/format-double-to-2-decimal-places-java/