Swift example converting a string to a currency by way of an Integer then back to a formatted string


  • Share on Pinterest

This post is based on my response to a Reddit question, the question was.

New to swift, trying to make a simple app to count money, getting “cannot assign value of type ‘int' to type ‘String?' error

The answer is actually simpler than you might think once you discover the power of the NumberFormatter built into the Swift language. Using the formatter you can convert a number to many different currencies with a customized appearance using just a small amount of code.

My answer was to make a function that could be called that would do the heavy lifting for you, all you need to do is provide it an int and it will convert and format the number, then return it as a string ready to be displayed.

Here is the function.

func convertIntToCurrencyAsString(intValue: Int) -> String {
	var stringVersion: String
	let cFormatter = NumberFormatter()
	cFormatter.usesGroupingSeparator = true
	cFormatter.numberStyle = .currency
	if let currencyString = cFormatter.string(from: NSNumber(value: intValue)) {
	stringVersion = currencyString
	} else {
	stringVersion = "Invalid Message"
	}
	return stringVersion
}

Just call the function, for example

convertIntToCurrencyAsString(123456)

This would return you the string “$123,456.00”

Hope this helps someone else, happy converting!

GitHub Repository with working example here