Skip to content

Instantly share code, notes, and snippets.

@martinlexow
Last active June 10, 2021 17:23
Show Gist options
  • Save martinlexow/8779910f7be9cdaf1cd2a5cecf6bbeda to your computer and use it in GitHub Desktop.
Save martinlexow/8779910f7be9cdaf1cd2a5cecf6bbeda to your computer and use it in GitHub Desktop.
import Foundation
func makeFormatted(price: String) -> String? {
// Convert Input Value To Number
let inputFormatter = NumberFormatter()
inputFormatter.locale = Locale(identifier: "en") // if you expect something like '3.14'
inputFormatter.allowsFloats = true
if let number = inputFormatter.number(from: price) {
// Format Number
let outputFormatter = NumberFormatter()
outputFormatter.locale = Locale.current
outputFormatter.allowsFloats = true
outputFormatter.minimumFractionDigits = 3
return outputFormatter.string(from: number)
} else {
print("Error: Unable to convert input value to number.")
return nil
}
}
makeFormatted(price: "3.14")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment