I'm trying to figure out how to round my division results to the nearest integer. I thought it would be fairly straight forward but obviously I'm not doing something right.

I wrote this extremely basic Android app for my wife and the formula requires that if there are any remainders or fractions, that the result needs to round to the nearest integer, so when it's multiplied by another variable, the final result will be correct. Instead, it always rounds down, which I'm certain is because I was initially using the INT type. But when I try to use DOUBLE for the variable, the remaining calculations that also rely on that variable give me an error: Incompatible Types, required INT, found: DOUBLE.

Can you not calculate mixed number types, such as integers with double or floating types?

Here is my calculation part of my code if anyone can shed some insight:

Also, what do you want 0.5 to round to - 0.0 or 1.0 ? Some implementations will round odd halves up and even halves down, or vice-versa, or always down, or always up. Which you use depends on you needs - odd/even rounding is used to try and achieve a zero net bias in the long run.

Mike Tompson wrote:I wrote this extremely basic Android app for my wife and the formula requires that if there are any remainders or fractions, that the result needs to round to the nearest integer, so when it's multiplied by another variable, the final result will be correct. Instead, it always rounds down, which I'm certain is because I was initially using the INT type. But when I try to use DOUBLE for the variable, the remaining calculations that also rely on that variable give me an error: Incompatible Types, required INT, found: DOUBLE.

Can you not calculate mixed number types, such as integers with double or floating types?

Well, you can't assign a

`double`to an

`int`without casting it, if that's what you mean; and since

`calculatedValue`is a

`double`, any expression that includes it will be a

`double`.

Here is my calculation part of my code if anyone can shed some insight:

Here you go. I've basicially copied your code and made a few adjustments. Explanations below:1. The extra method is just to save typing, but you might find a use for it elsewhere.

2. Don't declare variables and

*then*initialise. Do both at once.

3.

`calculatedValueC1`and

`calculatedValueC2`are part of

`calculatedValue`, so why write out the expressions twice?

4. As I explained above the last two expression have to be cast to

`int`before you can assign them.

And one general point:

5. Your variable names are either excessively long or short, and really don't mean anything to anyone reading your program.

HIH

Winston

"Leadership is nature's way of removing morons from the productive flow" - Dogbert

Articles by Winston can be found here

It is sorta covered in the JavaRanch Style Guide. |