The Miotz The Miotz - 1 year ago 147
iOS Question

iOS Swift: Formatting a custom Currency Number

Formatting large numbers with comma separator.

Solved (The code is updated and fully working)

Evening, I have a typealias

I want to print it with the comma between the thousands.

this is what I did:

import Foundation

typealias Currency = Double

extension Currency {
var credit: Double { return self }
var usd: Double { return self * 0.62 }

func description() -> String {
let price = self as NSNumber
let formatter = NumberFormatter()
formatter.numberStyle = .currency
return formatter.string(from: price)!


let price: Currency = 1000000000

/* It doesn't work, I want something like 1000,000,000.0 */

But it doesn't work. What is wrong?

Answer Source

description is a property that comes baked into Foundation via the CustomStringConvertible protocol which states the description variable as:

A textual representation of the value.

You're looking to call your description() method. Add parentheses and you'll get your desired result:


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download