Ad space (banner)
๐ŸฆSwift Lessons
Lesson 45 / 68

Rounding Numbers (rounded)

In this lesson you will learn how to round numbers in Swift with rounded, and pick the right mode for the job. This is for anyone searching for "Swift rounded how to use".

.rounded(.down) rounds down, .rounded(.up) rounds up, and .rounded() rounds to nearest. "Shave it down", "push it up", and "go to whichever is closer" are useful mental labels.

The sample code shows how similar-looking decimals give different results: (3.7).rounded(.down) gives 3.0, (3.2).rounded(.up) gives 4.0, and (3.5).rounded() gives 4.0.

A common stumbling block for beginners is that the result stays a Double. If you want an integer you need a further Int() conversion. To round to a set number of decimal places, there is a technique combining multiplication and division.

In real-world development the choice changes your results - handling fractions in monetary calculations, lining up decimal places for display - so pick deliberately.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)