Hello I am making a calculator app and I need a way to round the answer to the second number
Asked
Active
Viewed 1,146 times
1
-
possible duplicate of [Rounding in Swift with round()](http://stackoverflow.com/questions/25513357/rounding-in-swift-with-round) – ahruss Jul 01 '15 at 03:31
2 Answers
4
If you need to round just for display, you can use either NSNumberFormatter or String formatting capability:
let number = 123.456789
let formatter = NSNumberFormatter()
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 2
formatter.stringFromNumber(number) // "123.46"
String(format: "%.2f", number) // "123.46"

MirekE
- 11,515
- 5
- 35
- 28
1
Double(round(num*100)/100)
Should work. The way this works is first it multiplies by 100, which shifts all of the digits over to the left two places. Then it rounds based on the first decimal digit which is now the thousandths place. Then dividing by 100 again will shift everything to the right two decimal places.
This is the same as if you had just looked at the thousandths place and rounded to the nearest hundredth based on that (which is how a human would do it)

ezig
- 1,219
- 1
- 10
- 15
-
-
`func roundToHundreth(num: Double) -> Double { return Double(round(num*100)/100) }` – ezig Jul 01 '15 at 13:59