Skip to content

Instantly share code, notes, and snippets.

@mobibob
Created March 30, 2023 19:10
Show Gist options
  • Save mobibob/f78c141a3ea8fd3575ca62a169a99907 to your computer and use it in GitHub Desktop.
Save mobibob/f78c141a3ea8fd3575ca62a169a99907 to your computer and use it in GitHub Desktop.
SwiftUI decimal (Double) formatter as-if in a calculator.
import Foundation
import SwiftUI
struct Calculator: View {
func fmtDouble(dbl: Double) -> String? {
let formatter = NumberFormatter()
formatter.numberStyle = .currencyAccounting
formatter.minimumFractionDigits = 3
formatter.formatWidth = 70
return formatter.string(from: dbl as NSNumber)
}
/*
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
let number = NSNumber(value: value)
let formattedValue = formatter.string(from: number)!
*/
var body: some View {
VStack(alignment: .trailing) {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
Text("Calculator")
Divider()
Text(fmtDouble(dbl: 12.34)!)
Text(fmtDouble(dbl: Double(-3451.789))!)
Text(Double(-3451.789).debugDescription)
}
.padding()
.fixedSize(horizontal: true, vertical: true)
}
}
struct Calculator_Previews: PreviewProvider {
static var previews: some View {
Calculator()
}
}
@mobibob
Copy link
Author

mobibob commented Mar 30, 2023

image

@mobibob
Copy link
Author

mobibob commented Mar 30, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment