Reputation: 931
Hello I am making a calculator app and I need a way to round the answer to the second number
Upvotes: 1
Views: 1243
Reputation: 11555
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"
Upvotes: 4
Reputation: 1229
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)
Upvotes: 1