3

here's my example:

double num = 0;

num = 4/3;


System.out.println(num);

And my output is 1.0 instead of 1.3

Any suggestions?

Thorsten S.
  • 4,144
  • 27
  • 41
Jcorretjer
  • 467
  • 2
  • 6
  • 24

4 Answers4

9

Don't do int division since this always will result in a truncated int. Instead have your division use at least one double value.

double num = 4.0/3.0;

Then when you want to display it as a String, format the output so you can choose your decimal places:

// one way to do it
// %.3f is for a floating number with 3 digits to the right of the decimal
// %n is for new line
System.out.printf(%.3f%n, num); 

Another:
DecimalFormat decimalFormat = new DecimalFormat("0.000");
System.out.println(decimalFormat.format(num));
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 1
    Well you only need to have one be a double (like 4.0/3 or 4/3.0), but both can't hurt :) +1 – Alex Coleman Oct 02 '12 at 02:50
  • 1
    @HovercraftFullOfEels Yeah, or 4d/3 :P – Alex Coleman Oct 02 '12 at 02:53
  • I had tried DecimalFormat and BigDecimal too and didn't work :/ They never tough me this in college >:( I'm way better at C++, still kinda new to java and they told me "it's the same thing so... don't worry :D" BS! thanks again – Jcorretjer Oct 02 '12 at 02:55
1

Write

num=(double)4/3;

It will return 1.3333.... Then you can round off the decimals

user14678216
  • 2,886
  • 2
  • 16
  • 37
0

You should also use String.format(%1.2f, yourDouble) to format your decimal places

  • 3
    Yes, this code will print the double data, but check that `int/int = int`, so `4/3` will be `1`, you should use `4.0/3.0` in order to get `1.333...` – Luiggi Mendoza Oct 02 '12 at 02:57
0

Try this..

double value= 255.956666;

BigDecimal bd = new BigDecimal(value).setScale(2, RoundingMode.HALF_UP);
System.out.println("value="+bd);
Abhinav Singh Maurya
  • 3,313
  • 8
  • 33
  • 51