programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

Rounding Integers

Troy Peterson
Greenhorn
Posts: 6
Hey guys I need to round my variables to the nearest "tens" place and I'm having trouble doing so. Every time I run the program it comes back with a number ending in .0 even if its something like 11 / 3. How can I fix this?

Paul Clapham
Sheriff
Posts: 22829
43

1. Take two integers and divide one by the other. The result is an integer: for example 11 / 3 yields 3.

2. Multiply by 10. (Yields 30 in this example)

3. Round to the nearest integer. (Yields 30 again)

4. Divide by 10. (Yields 3 again)

I'm assuming that when you say you want to round to the nearest "tens" place you don't actually want to round 257.325 to 260. I'm assuming you actually want to round it to the nearest tenth, which would be 257.3? If that's the case then it's only step 1 in your calculation which is throwing it off.

Troy Peterson
Greenhorn
Posts: 6
Yes, sorry about the misunderstanding. I want the "tenth" place

Paul Clapham
Sheriff
Posts: 22829
43
Okay. So you've just fallen into the "integer division" trap like most beginners do. Dividing one int by another int results in an int value, and the remainder is just thrown away. Which isn't what you want. So convert one of the ints to double before you do the division.