-2

when I do this

    double money = 2.3452;
    DecimalFormat decFor = new DecimalFormat("0.00");
    System.out.println(decFor.format(money));

I get this output: 2.35

But when I do this

    double money = 1/8;
    DecimalFormat decFor = new DecimalFormat("0.00");
    System.out.println(decFor.format(money));

I get: 0.00

How to make Java to show you 0.12 instead of 0.00?

user2838743
  • 11
  • 1
  • 3

2 Answers2

5

Do this:

double money = 1.0 / 8;

The problem is that you are taking the integer, 1 and dividing it by an integer, 8. Java then uses integer math, which truncates to 0. If you use 1.0 explicitly, then it will use floating point division.

caveman
  • 1,755
  • 1
  • 14
  • 19
0

You need to cast to double. In integer division the fractional part of the result is thrown away.

double money = (double)1/8;
DecimalFormat decFor = new DecimalFormat("0.00");
System.out.println(decFor.format(money));
arsenal
  • 23,366
  • 85
  • 225
  • 331