Skip to content

Instantly share code, notes, and snippets.

@popeyelau
Last active March 19, 2020 05:23
Show Gist options
  • Save popeyelau/e53987e59190e7a3ead8a2ce1d70197e to your computer and use it in GitHub Desktop.
Save popeyelau/e53987e59190e7a3ead8a2ce1d70197e to your computer and use it in GitHub Desktop.
Swift Number formatter|-|{"files":{"Number+Extension.swift":{"env":"plain"}},"tag":"Gists"}
extension Formatter {
static let number = NumberFormatter()
}
extension FloatingPoint {
func fractionDigits(min: Int = 2, max: Int = 2, roundingMode: NumberFormatter.RoundingMode = .down) -> String {
Formatter.number.minimumFractionDigits = min
Formatter.number.maximumFractionDigits = max
Formatter.number.roundingMode = roundingMode
Formatter.number.numberStyle = .decimal
return Formatter.number.string(for: self) ?? ""
}
}
extension String {
var doubleValue: Double? {
return Formatter.number.number(from: self)?.doubleValue
}
var intValue: Int? {
return Formatter.number.number(from: self)?.intValue
}
var floatValue: Float? {
return Formatter.number.number(from: self)?.floatValue
}
}
let number: Double = 1.4988
number.fractionDigits() //1.49
number.fractionDigits(min: 2, max: 3, roundingMode: .down) //1.498
number.fractionDigits(min: 2, max: 3, roundingMode: .up) //1.499
let string = "123.88"
string.doubleValue //123.88
string.intValue //123
string.floatValue //123.88
string.floatValue?.fractionDigits(min: 1, max: 1, roundingMode: .up) //123.9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment