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 ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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 ?

23rd Jan 2022, 5:52 AM
Davinder Kumar
Davinder Kumar - avatar
8 Answers
+ 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/
23rd Jan 2022, 7:25 AM
Anannya
+ 5
Here, you defined your return type as double not parameters(numbers) that you used to calculate the average. double Number1, double Number2....
23rd Jan 2022, 7:06 AM
Simba
Simba - avatar
+ 3
It should print as you expected. double x = 2222; double y = 100; System.out.println(x/y); How did you do that?
23rd Jan 2022, 5:59 AM
Simba
Simba - avatar
+ 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 } }
23rd Jan 2022, 6:32 AM
Davinder Kumar
Davinder Kumar - avatar
+ 2
11.6666666666 but i want 11.66 🙂by the way thanks you
23rd Jan 2022, 7:18 AM
Davinder Kumar
Davinder Kumar - avatar
+ 1
Actually i have done this case but when it comes to (23.65). I'm getting 23.0
23rd Jan 2022, 6:11 AM
Davinder Kumar
Davinder Kumar - avatar
+ 1
Thank you Hazel i got my answer now
23rd Jan 2022, 8:15 AM
Davinder Kumar
Davinder Kumar - avatar
+ 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/
24th Jan 2022, 3:47 PM
Азизов И. А.
Азизов И. А. - avatar