Last active
December 17, 2017 13:16
-
-
Save simonbromberg/a6f2de7b13c16436902c342172d1de9d to your computer and use it in GitHub Desktop.
Rounding in Swift, adapted from: http://www.globalnerdy.com/2016/01/26/better-to-be-roughly-right-than-precisely-wrong-rounding-numbers-with-swift/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Double { | |
// Given a value to round and a factor to round to, | |
// round the value to the nearest multiple of that factor. | |
mutating func round(toNearest: Double) { | |
self = (self / toNearest).rounded() * toNearest | |
} | |
// Given a value to round and a factor to round to, | |
// round the value DOWN to the largest previous multiple | |
// of that factor. | |
mutating func roundDown(toNearest: Double) { | |
self = floor(self / toNearest) * toNearest | |
} | |
// Given a value to round and a factor to round to, | |
// round the value DOWN to the largest previous multiple | |
// of that factor. | |
mutating func roundUp(toNearest: Double) { | |
self = ceil(self / toNearest) * toNearest | |
} | |
// Round the given value to a specified number | |
// of decimal places | |
mutating func round(toDecimalPlaces places: Int) { | |
let divisor = pow(10.0, Double(places)) | |
self = (self * divisor).rounded() / divisor | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment