Skip to content

Instantly share code, notes, and snippets.

@simonbromberg
Last active December 17, 2017 13:16
Show Gist options
  • Save simonbromberg/a6f2de7b13c16436902c342172d1de9d to your computer and use it in GitHub Desktop.
Save simonbromberg/a6f2de7b13c16436902c342172d1de9d to your computer and use it in GitHub Desktop.
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