Allen Gingrich
Allen Gingrich

Reputation: 5657

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();

            }

Upvotes: 2

Views: 3203

Answers (7)

LarsH
LarsH

Reputation: 27994

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.

Upvotes: 1

JeremyP
JeremyP

Reputation: 86651

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.

Upvotes: 2

nos
nos

Reputation: 229108

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

((double)l / h)

Upvotes: 4

Jes
Jes

Reputation: 2778

(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.

Upvotes: 9

Adam
Adam

Reputation: 3795

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.

Upvotes: 2

atk
atk

Reputation: 9314

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

Upvotes: 1

Dave McClelland
Dave McClelland

Reputation: 3413

double val = ((double)l)/h

Upvotes: 4

Related Questions