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) Types Numbers and Booleans

Marcus Wilhoit
Marcus Wilhoit
400 Points

What happens to Floats that have numbers with more than 7 decimal places or Doubles with more than 15? Are they Rounded?

Are the numbers Rounded? Is there an error that occurs? How does Swift handle these cases?

3 Answers

Jason Lysinger
Jason Lysinger
8,106 Points

The simple answer is Yes... they get rounded.

You can test this in a playground and see the results.

var myDouble = 10.12345678912345

the output would be 10.1234567891235 thus the last digit being rounded up.

Mike Atkinson
Mike Atkinson
6,882 Points

Yes, the double will get rounded nicely rounded with the last number it can display, however declaring a float with too many digits seems to return a messy number.

I'm thinking this might be to do with the amount of memory allocated for each type. If I'm correct, in Swift a float is allocated 4 bytes of memory and a double is allocated 8 bytes of memory. This doesn't mean the amount if digits they hold, but possible combinations they can hold. Literally thousands of combinations.

Anyway, perhaps if the float is filled with too many digits, it looses the ability to properly hold the information? Then again, why does the double get rounded, and the float not?

Sorry, maybe not answering OPs question, but expanding on discussion.

Michael Hulet
Michael Hulet
47,913 Points

It's not exactly rounding, but kind of. When the computer's hardware can only technically represent whole 1s and 0s, representing decimals gets a little hard, especially since a computer only has a finite amount of space to store it in (though doubles have double the amount of space that floats do (understand why they're called doubles?)). It's really similar to Scientific Notation, if you remember that from High School science class, but it's Scientific Notation in an entirely different system of counting. If you want to learn exactly what's going on, Computerphile made a great video on the topic