Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java does not print decimal places [duplicate]

Tags:

java

I'm trying to do a very basic operation as follows:

double a=21/5;
System.out.println(a);

However, each time I get 4.0 as the output and not 4.2. I'm encountering this for the first time. I've been using Java for years, but never came across this obscurity.

like image 266
xan Avatar asked Dec 02 '25 06:12

xan


1 Answers

You are using integer division, which result will always be integer You should use something like this.

double a=(double)21/5;
like image 174
Arsen Alexanyan Avatar answered Dec 04 '25 18:12

Arsen Alexanyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!