Skip to content

Instantly share code, notes, and snippets.

@jimbrayrcp
Last active April 22, 2022 04:40
Show Gist options
  • Save jimbrayrcp/91e33c63a6abc9b091455eadb5b8f393 to your computer and use it in GitHub Desktop.
Save jimbrayrcp/91e33c63a6abc9b091455eadb5b8f393 to your computer and use it in GitHub Desktop.
Dynamically removes trailing zeros from doubles in swiftui view text fields. To use a (let) type extension instead use: snippetslab://snippet/ABECB304-F4B9-451A-A47D-69602E7F56A6/
struct RowView: View {
var coin: Coins
var body: some View {
VStack() {
let _ = print("\((Double("\(coin.paymentThreshold)")!.dynamicDrecimalFormat())) ")
HStack(alignment: .bottom) {
Spacer()
Text("\((Double("\(coin.paymentThreshold)")!.dynamicDrecimalFormat())) ")
Text(coin.symbol ?? "")
.font(.footnote)
}
}
}
}
extension Double {
func dynamicDrecimalFormat() -> String {
let formatter = NumberFormatter()
let number = NSNumber(value: self)
formatter.numberStyle = .decimal
formatter.groupingSeparator = ","
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 16
return String(formatter.string(from: number) ?? "")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment