The Money documentation provides detailed information on how to use the Money library in your iOS projects. Money is a powerful and flexible library for working with money-related operations and calculations.
Features
- Supports multiple currencies
- Handles arithmetic operations with precision
- Formatting and parsing of monetary values
- Conversion between different currencies using exchange rates
- Supports localization and formatting based on locale
Installation
To integrate the Money library into your project, follow these steps:
- Add the following line to your
Podfile
:
“`ruby
pod ‘money’
“`
- Run the command
pod install
in the terminal to install the library. - Import the library in your code file:
“`swift
import Money
“`
Usage
Creating Money Instances
To create a Money instance, use the following code:
“`swift
let amount = Money(amount: 15, currency: .usd)
“`
Arithmetic Operations
You can perform arithmetic operations on Money instances using the following methods:
- Adding: Use the
+
operator or theplus
method. - Subtracting: Use the
-
operator or theminus
method. - Multiplying: Use the
*
operator or thetimes
method. - Dividing: Use the
/
operator or thedivided
method.
“`swift
let sum = amount + Money(amount: 10, currency: .usd) // or use the plus method
let difference = amount – Money(amount: 5, currency: .usd) // or use the minus method
let product = amount * 2 // or use the times method
let quotient = amount / 3 // or use the divided method
“`
Formatting and Parsing
You can format Money instances as strings using the formatted
property or the format()
method:
“`swift
let formattedAmount = amount.formatted // $15.00
let customFormat = amount.format(locale: Locale(identifier: “en_GB”)) // £15.00
“`
To parse a string and convert it to a Money instance, use the parse()
method:
“`swift
let parsedAmount = Money.parse(“-$50.99”, locale: Locale(identifier: “en_US”)) // Money(amount: -50.99, currency: .usd)
“`
Currency Conversion
The Money library supports currency conversion using exchange rates. To convert an amount from one currency to another, use the convertTo()
method:
“`swift
let convertedAmount = amount.convertTo(.eur, rate: 0.83) // converts to Euro using the given rate
“`
Localization
The library supports localization of money formatting based on the user’s locale. To format a Money instance based on the user’s locale, use the locale
property or the format()
method:
“`swift
let localizedAmount = amount.format(locale: Locale.current) // uses the user’s current locale for formatting
“`
Conclusion
The Money library offers a comprehensive solution for working with money-related operations in iOS projects. With support for multiple currencies, precision arithmetic, formatting, parsing, and currency conversion, it simplifies the complexities of monetary calculations. Start integrating the Money library into your projects and handle money operations effortlessly!