How to format currency in Swift

Issue #355

1
2
3
4
5
6
7
8
9
10
11
12
final class CurrencyFormatter {
func format(amount: UInt64, decimalCount: Int) -> String {
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = decimalCount
formatter.numberStyle = .decimal

let value = Double(amount) / pow(Double(10), Double(decimalCount))
let fallback = String(format: "%.0f", value)
return formatter.string(from: NSNumber(value: value)) ?? fallback
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
class CurrencyFormatterTests: XCTestCase {
func testFormat() {
let formatter = CurrencyFormatter()
// 120 USD
XCTAssertEqual(formatter.format(amount: 120, decimalCount: 0), "120")

// 12000 cents
XCTAssertEqual(formatter.format(amount: 12000, decimalCount: 2), "120")

// 12520 cents
XCTAssertEqual(formatter.format(amount: 12520, decimalCount: 2), "125.2")
}
}

Comments