Based on the value of a Double I want to format in a specific way:
let values = [
0.0000252997958320863,
0.0012252997958320863,
0.0004252997958320863,
1.911231231231232131231,
1120.212312313
]
Can anyone advise how I can format the display value so that it will show the number of zeros up to the first number, i.e.:
let formattedValues = [
"0.00002",
"0.001",
"0.0004",
"1.91",
"1,120.21"
]
These are values of cryptocurrencies, being retrieved from an API, so I want to display as such. I want to have at least 2 decimal places, and not be “0.00” unless the number itself is 0.
By using Text("(value, specifier: "%.2f")")
works fine when it is 1234567, as it will display 12,345.67
but if the value is 0.000004
it will show 0.00
This is what I have come up with so far, but it isn’t working correctly.
extension Double {
func formatPrice() -> String {
// Format number with high precision
let stringValue = String(format: "%.20f", self)
// Split the string into integer and fractional parts
let components = stringValue.split(separator: ".")
guard components.count == 2 else {
// If there's no fractional part, return the formatted string
return stringValue
}
let integerPart = components[0]
var fractionalPart = components[1]
// Remove trailing zeros from the fractional part
while fractionalPart.last == "0" {
fractionalPart.removeLast()
}
// Find the first non-zero character in the fractional part
if let firstNonZeroIndex = fractionalPart.firstIndex(where: { $0 != "0" }) {
// Calculate the end index to include two digits after the first non-zero
let endIndex = fractionalPart.index(firstNonZeroIndex, offsetBy: 2, limitedBy: fractionalPart.endIndex) ?? fractionalPart.endIndex
// Form the final fractional string
let significantFraction = fractionalPart[..<endIndex]
// Combine integer and significant fractional parts
let significantPart = "(integerPart).(significantFraction)"
// Use NumberFormatter to add commas to the integer part
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
if let formattedNumber = numberFormatter.string(from: NSNumber(value: Double(significantPart)!)) {
return formattedNumber
}
return significantPart
} else {
// If there are no non-zero digits, return the integer part
return "(integerPart)"
}
}
}
5