How to make 100 divided by 110 equal a decimal in Java / Android

I'm trying to use the follow code to produce a decimal number, but the evaluation of l divided by h (low by high) always comes out to be 0.

How can I correct this? Thanks!

EditText marketValLow = (EditText) findViewById(R.id.marketValLow); EditText marketValHigh = (EditText) findViewById(R.id.marketValHigh); String valLow = marketValLow.getText().toString(); String valHigh = marketValHigh.getText().toString(); int l = Integer.parseInt(valLow); int h = Integer.parseInt(valHigh); if (valLow.trim().equals("") || valHigh.trim().equals("")) { Toast.makeText(CurrentMarketValue.this, "You need to enter a high AND low." + valLowIndex, Toast.LENGTH_SHORT).show(); } else if ((l / h) < .9) { Toast.makeText(CurrentMarketValue.this, "The range between your value cannot be more than 10%." + (l / h), Toast.LENGTH_SHORT).show(); }
1

7 Answers

(int / int) will result in a int.

Instead do: double result = ((double)l) / ((double) h); and instead of checking on (l / h) do a check on result instead.

1
double val = ((double)l)/h

You're doing integer division. Force one of the operands of / to be a double.

((double)l / h)

it is a basic part of many type languages. Integer division shows the results of whole divisions. In your case you could make it 1.0 / h or typecast one of the numbers to float or double.

Just by way of contrast to all the other answers:

if ((l * 10) < (h * 9))

Not saying its better (in fact if l or h has the possibility of being greater than about 200 million it's bad), just different.

4

It would appea ryou're using an integer where a float or double would be better.

I think JeremyP is right. TomTom why do you say it's wrong? The following are all equivalent, by properties of inequalities (multiplying both sides by the same positive amount... assuming h >= 0):

(l / h) < .9
l < (.9 * h)
(l * 10) < (h * 9)

The latter also has the nice property of not throwing an exception when h = 0.

4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like