• Post Reply Bookmark Topic Watch Topic
  • New Topic

Rounding Integers  RSS feed

 
Troy Peterson
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your calculation:

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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, sorry about the misunderstanding. I want the "tenth" place
 
Paul Clapham
Sheriff
Posts: 22829
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!