Skip to content

Instantly share code, notes, and snippets.

@khanlou
Last active December 13, 2016 16:36
Show Gist options
  • Select an option

  • Save khanlou/613cee8eb692c0d965650a30003869a2 to your computer and use it in GitHub Desktop.

Select an option

Save khanlou/613cee8eb692c0d965650a30003869a2 to your computer and use it in GitHub Desktop.
extension BinaryFloatingPoint {
func rounded(to radix: Self) -> Self {
return (self/radix).rounded(.toNearestOrAwayFromZero)*radix
}
}
(55.325).rounded(to: 1/10) // => 55.3
extension SignedInteger {
func rounded(to radix: Self) -> Self {
let truncated = self/radix*radix
let distanceToTrunctation = self - truncated
if distanceToTrunctation < radix - distanceToTrunctation {
return truncated
} else {
return truncated + radix
}
}
}
13.rounded(to: 2)
1499.rounded(to: 1000)
1501.rounded(to: 1000)
1500.rounded(to: 1000)
12.rounded(to: 10)
15.rounded(to: 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment