0

I have something like this:

int mls = 400; // 400 milliliters

I'd like to show 0,4 for users (0,4... 0,8... 1,0 ... 1,2...)

I try to divide mls by 1000:

mls = 400 / 1000;

TextView todayValue = findViewById(R.id.todayValue);
        todayValue.setText(String.valueOf(mls));

it gives me 0 as a result.

any ideas how to convert milliliters to liters showing to user something like 0,4 liters???

RGS
  • 4,062
  • 4
  • 31
  • 67

2 Answers2

2

The idea is, you are first doing a / b, and because it's an integer operation, it'll round the result to 0. Doing a * 100 first should fix it.

From:Dividing two integers in Java gives me 0 or 100?

Djaf
  • 256
  • 1
  • 6
2

You should try it with another primitive type since int doesn't cover decimals.

Other options are, for instance, Double, Float, Long

So instead of declaring your variable as int mls = 400 you could do it as double mls = 400.

Another solution could be using a decimal at the operation, like 400.0 / 1000.0

Joan
  • 321
  • 1
  • 10