Last active
December 13, 2016 16:36
-
-
Save khanlou/613cee8eb692c0d965650a30003869a2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 BinaryFloatingPoint { | |
| func rounded(to radix: Self) -> Self { | |
| return (self/radix).rounded(.toNearestOrAwayFromZero)*radix | |
| } | |
| } | |
| (55.325).rounded(to: 1/10) // => 55.3 |
This file contains hidden or 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 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