+ 2

Why System.out.println(450/100) gives me 4 as a result and not 4.5?

I'm new to Java but that strange behavior makes my attempts to learn Java miserable.

10th Mar 2017, 9:34 AM
Emo Pandov
Emo Pandov - avatar
4 Answers
+ 8
In Java and some other programming languages, dividing two whole numbers gives you a whole number result. In this case, the answer is 4.5, but since the result must be a whole number, the 0.5 is truncated and you get 4. If you want a double result, cast one of the numbers to double, or write one as a double. Ex: 450 / 100.0
10th Mar 2017, 9:48 AM
Tamra
Tamra - avatar
+ 6
Reply to Emo: What about when I use variable Same...As Tamra's Ex... double var = 450.0/100.0 or float var = 450.0/100.0 or auto var = 450.0/100 //This is c++ or Object var = 450.0/100
10th Mar 2017, 10:07 AM
Yanothai Chaitawat
Yanothai Chaitawat - avatar
+ 1
//you can try System.out.println((double)450/100); // 4.5 //As int can not have decimal values
10th Mar 2017, 11:31 AM
Vishal Prajapati
0
What about when I use variables?
10th Mar 2017, 9:52 AM
Emo Pandov
Emo Pandov - avatar