Skip to content

Instantly share code, notes, and snippets.

@natelowry
Last active March 12, 2025 16:20
Show Gist options
  • Save natelowry/400485daacb4287d34065083f6dec908 to your computer and use it in GitHub Desktop.
Save natelowry/400485daacb4287d34065083f6dec908 to your computer and use it in GitHub Desktop.
Swift number formatting, rounding, and validation extensions
print("Pi Time: \(3.14.f(3))")
let myNumber = 4.20 / 6.9
print("the answer is \(myNumber.f(5))")
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