How to represent currency in Swift

1 Answer

0 votes
/*---------------------------------------------------------
  Description:
    Demonstrates how to represent and display currency
    values in idiomatic Swift using NumberFormatter.
---------------------------------------------------------*/

import Foundation

// Currency formatter for US dollars
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale(identifier: "en_US")

// Price and tax rate
let price: Double = 199.99
let taxRate: Double = 0.17   // 17%

// Calculate tax and total
let taxAmount = price * taxRate
let total = price + taxAmount

// Output with $ and % signs
print("Price: \(formatter.string(from: price as NSNumber)!)")
print("Tax Rate: 17%")
print("Tax Amount: \(formatter.string(from: taxAmount as NSNumber)!)")
print("Total: \(formatter.string(from: total as NSNumber)!)")



/*
run:

Price: $199.99
Tax Rate: 17%
Tax Amount: $34.00
Total: $233.99

*/

 



answered 12 hours ago by avibootz
...