I want to format decimals to have four non-zero numbers after the final 0. For example, 0.001765 or 0.00004839 .
Any numbers above 1 would simply have two decimals. For example, 2.23 .
I am wondering if I can accomplish this using NumberFormatter?
I want to format decimals to have four non-zero numbers after the final 0. For example, 0.001765 or 0.00004839 .
Any numbers above 1 would simply have two decimals. For example, 2.23 .
I am wondering if I can accomplish this using NumberFormatter?
Use the maximumSignificantDigits
property.
let nf = NumberFormatter()
nf.maximumSignificantDigits = 4
print(nf.string(for: 0.00000232323)!)
// prints 0.000002323
print(nf.string(for: 2.3)!)
// prints 2.3
You have two conditions. Use the minimumSignificantDigits
and maximumSignificantDigits
for the 4 digits and use maximumFractionDigits
for the 2 places for values over 1.
extension FloatingPoint {
func specialFormat() -> String {
let fmt = NumberFormatter()
fmt.numberStyle = .decimal
if abs(self) >= 1 {
// adjust as needed
fmt.maximumFractionDigits = 2
} else {
fmt.minimumSignificantDigits = 4
fmt.maximumSignificantDigits = 4
}
return fmt.string(for: self)!
}
}
print(0.001765345.specialFormat())
print(0.00004839643.specialFormat())
print(1.2345.specialFormat())
Output:
0.001765
0.00004840
1.23
I used a combination of the answers / comments received to optimally solve this problem.
First, the two necessary formatters as static properties via an extension (as suggested by Leo).
extension Formatter {
static let twoDecimals: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
return formatter
}()
static let fourSigDigits: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumSignificantDigits = 4
formatter.maximumSignificantDigits = 4
return formatter
}()
}
Then, an extension to conditionally apply the proper formatter (as suggest by rmaddy):
extension FloatingPoint {
var currencyFormat: String {
return abs(self) >= 1 ?
Formatter.twoDecimals.string(for: self) ?? "" :
Formatter.fourSigDigits.string(for: self) ?? ""
}
}
Finally, you can use it like so:
let eth = 1200.123456
let xrp = 1.23456789
let trx = 0.07891234
eth.currencyFormat //"1200.12"
xrp.currencyFormat //"1.23"
trx.currencyFormat //"0.07891"