Last active
March 12, 2025 16:20
-
-
Save natelowry/400485daacb4287d34065083f6dec908 to your computer and use it in GitHub Desktop.
Swift number formatting, rounding, and validation extensions
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
| print("Pi Time: \(3.14.f(3))") | |
| let myNumber = 4.20 / 6.9 | |
| print("the answer is \(myNumber.f(5))") |
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
| import Foundation | |
| extension Double { | |
| func roundTo(_ places: Int) -> Double { | |
| let divisor = pow(10.0, Double(places)) | |
| return (self * divisor).rounded() / divisor | |
| } | |
| var isValidInt: Bool { | |
| if self >= Double(Int.max) || self < Double(Int.min) || self.isNaN || self.isInfinite { | |
| return false | |
| } | |
| return true | |
| } | |
| func f(_ numberOfFractionalDigits: Int) -> String { | |
| self.formatted(.number.precision(.fractionLength(numberOfFractionalDigits))) | |
| } | |
| } | |
| extension Float { | |
| var isValidInt: Bool { | |
| if self >= Float(Int.max) || self < Float(Int.min) || self.isNaN || self.isInfinite { | |
| return false | |
| } | |
| return true | |
| } | |
| func f(_ numberOfFractionalDigits: Int) -> String { | |
| self.formatted(.number.precision(.fractionLength(numberOfFractionalDigits))) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment