Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift Basics (retired) Operators Binary Operators

Joe Lingle
Joe Lingle
686 Points

Rounding of Constant?

Add 9:18 he divides width/chairWidth which returns an answer of 3.
Since width = 10 and chairWidth = 3 the answer makes sense i.e. 3.3333 written as an integer is 3.

But when I changed width to 11, the program still returned a value of 3 for chairs even though 3.667 should round to 4.

Does the program always round down?

1 Answer

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

Hi, Joe Lingle

Does the program always round down?

No, it has nothing to do with rounding up or down. In Swift, and many other programming languages, when you're doing division where both the dividend and divisor are integers, the result will always be integer as well, the decimal part of the result, if any, will be completely discarded.

But when I changed width to 11, the program still returned a value of 3 for chairs even though 3.667 should round to 4.

In order to get the rounded result here, you have to do this

round(10/3.0)  //=> 3
round(11/3.0)  //=> 4

Make either dividend or divisor, or both, a floating point number, that way the division result will be a floating point number as well, then make to round() method to round the result to the nearest integer value.

Hope this helps.