Skip to content

Instantly share code, notes, and snippets.

@burhanaras
Created August 31, 2023 11:19
Show Gist options
  • Save burhanaras/c6df1c0cdea70f29fb57378f26b8e364 to your computer and use it in GitHub Desktop.
Save burhanaras/c6df1c0cdea70f29fb57378f26b8e364 to your computer and use it in GitHub Desktop.
import Foundation
enum CurrencyPosition {
case left
case right
case none
}
class Money {
// Properties
private var amount: Decimal
private var currencyCode: String
private var currencyPosition: CurrencyPosition
// Initializer
init(amount: Decimal, currencyCode: String, currencyPosition: CurrencyPosition = .right) {
self.amount = amount
self.currencyCode = currencyCode
self.currencyPosition = currencyPosition
}
// Methods
// Format money with a specified format
func format(decimalDigits: Int = 2) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencyCode = currencyCode
formatter.maximumFractionDigits = decimalDigits
var formattedAmount = formatter.string(from: amount as NSDecimalNumber) ?? ""
switch currencyPosition {
case .left:
break // Currency code is on the left by default
case .right:
formattedAmount = formattedAmount.replacingOccurrences(of: currencyCode, with: "").trimmingCharacters(in: .whitespaces)
case .none:
formattedAmount = formattedAmount.replacingOccurrences(of: currencyCode, with: "").trimmingCharacters(in: .whitespaces)
}
return formattedAmount
}
// Display the money as a formatted string
func display(decimalDigits: Int = 2) -> String {
return format(decimalDigits: decimalDigits)
}
}
// Example usage:
let moneyLeftCurrency = Money(amount: 100.50, currencyCode: "USD", currencyPosition: .left)
let moneyRightCurrency = Money(amount: 88.1775, currencyCode: "EUR")
let moneyNoCurrency = Money(amount: 1234.5678, currencyCode: "JPY", currencyPosition: .none)
let money2Digits = Money(amount: 456.78, currencyCode: "GBP", currencyPosition: .left)
let money3Digits = Money(amount: 789.123, currencyCode: "CAD", currencyPosition: .left)
let money4Digits = Money(amount: 123.4567, currencyCode: "AUD", currencyPosition: .left)
print(moneyLeftCurrency.format()) // Outputs: "USD 100.50"
print(moneyRightCurrency.format()) // Outputs: "88.1775 EUR"
print(moneyNoCurrency.format()) // Outputs: "1234.5678"
print(money2Digits.format()) // Outputs: "GBP 456.78"
print(money3Digits.format()) // Outputs: "CAD 789.123"
print(money4Digits.format()) // Outputs: "AUD 123.4567"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment