📜  numberformatter swift (1)

📅  最后修改于: 2023-12-03 15:33:13.836000             🧑  作者: Mango

NumberFormatter in Swift

NumberFormatter is a class in Swift that allows you to format numerical values as strings for display purposes.

Basic Usage

Here's a basic example of how to use NumberFormatter:

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
let number = 1234.567
let numberString = formatter.string(from: NSNumber(value: number))
print(numberString ?? "nil")

In the example above, we create a NumberFormatter instance and set its number style to .decimal. Then we define a number (1234.567) and convert it to a string using the formatter's string(from:) method. Finally, we print the string that was returned.

The output of the above code snippet would be 1,234.567.

Formatting Options

NumberFormatter has several formatting options that can be used to customize the output of the formatted number. Here are some examples:

Number Style
formatter.numberStyle = .currency

This sets the number style to currency, which includes a currency symbol and decimal places.

formatter.numberStyle = .percent

This sets the number style to percent, which multiplies the number by 100 and adds a percentage sign.

Currency Style Options
formatter.locale = Locale(identifier: "en_US")
formatter.currencyCode = "USD"

These options customize the currency symbol and formatting used by the formatter.

Significant Digits
formatter.maximumSignificantDigits = 3

This sets the maximum number of significant digits to 3. For example, the number 1234.567 would be formatted as 1,230.

Rounding Modes
formatter.roundingMode = .halfEven

This sets the rounding mode to Half-Even, which rounds the number to the nearest even digit when it is exactly halfway between two digits. Other rounding modes are available as well.

Conclusion

NumberFormatter is a useful tool for formatting numerical values as strings. Its various options allow you to customize the output to fit your needs.