How can i organise my string so it will look nearly like an original calculator. Basically curerntly i am using a string int he following format (String(format: "%.f")
My code Below
mutating func appendNumber(_ number: Double) {
if number.truncatingRemainder(dividingBy: 1) == 0 && currentNumber.truncatingRemainder(dividingBy: 1) == 0 {
currentNumber = 10 * currentNumber + number
} else {
currentNumber = number
}
}
}
struct Home: View {
let characterLimit = 9
//MARK: - Computed propety
var displayedString: String {
return String(String(format: "%.01f",
arguments: [state.currentNumber]).prefix(characterLimit))
}
I want it to have a spacing every 3 characters same as in the native calculator app from IOS.
You should use a NumberFormatter
. Example:
var displayedString: String {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return String((formatter.string(for: state.currentNumber) ?? "").prefix(characterLimit))
}
Note that the output is locale dependent. In one locale, it could output 123,456,789
. In another locale, it could be 123 456 789
, and in a third, it could be 123.456.789
. I'm pretty sure there are locales that use different group sizes. The Calculator app has this behaviour too. For the Calculator app on my phone for example, it uses commas, not spaces, as the separator.
If you want to use spaces every 3 digits for the grouping no matter where the phone's locale is set to, you can set it manually:
formatter.groupingSeparator = " "
formatter.groupingSize = 3