2 Ways to format decimal numbers in Swift

2 Ways to format decimal numbers in Swift

·

3 min read

In programming, formatting numbers is an important task that helps to present data in a more readable and user-friendly way. In Swift, there are several ways to format decimal places, including using string interpolation, NSNumberFormatter, and the Decimal struct. In this blog, we will explore each method with code examples.

The code in this post is available here.

Using String Interpolation formatter

One way to format decimal places in Swift is by using string interpolation. You can use the String(format: ) method to specify the number of decimal places you want to display. Here's an example:

extension Double {
    //MARK: - Using string interpolation
    func toString1(_ numOfDecimal: Int) -> String {
        return String(format: "%.\(numOfDecimal)f", self)
    }
}

In this example, we used the format specifier to indicate that we want to display how many decimal places after the decimal point. For instance, if the integer passed into the function is 2, the format specifier would be "%.2f" and the result of Double(3).toString1(2) is "3.00".

Using NSNumber Formatter

NumberFormatter is a class in Swift that allows you to format NSNumbers in various ways, including specifying the number of decimal places to display. Here's an example:

extension Double {
    //MARK: - Using NSNumberFormatter
    func toString2(_ numOfDecimal: Int) -> String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.maximumFractionDigits = numOfDecimal
        return formatter.string(from: self as NSNumber) ?? ""
    }
}

In this example, we created an instance of NumberFormatter and set the numberStyle property to .decimal to format the number with decimal separators. We also set the maximumFractionDigits property to 2 to display two decimal places after the decimal point, if numOfDecimal is 2.

Usage of the functions above

We can build a simple SwiftUI view to check how the function can be used.

struct ContentView: View {
    let pi = Double.pi
    @State private var digit: Int = 0
    var body: some View {
        NavigationView {

            VStack {
                Stepper("Number of digit (0-16)", value: $digit)
                    .onChange(of: digit) { newValue in
                        if newValue < 0 {
                            digit = 0
                        }
                        if newValue >= 16 {
                            digit = newValue - 1
                        }
                    }
                getRow("Unformatted", "\(pi)")
                getRow("String interpolation", pi.toString1(digit))
                getRow("NSNumberFormatter", pi.toString2(digit))
            }
            .padding(.horizontal, 20)
        }
    }
    func getRow(_ type: String, _ value: String) -> some View {
        VStack {
            Divider()
            HStack {
                Text(type).bold()
                Spacer()
                Text(value)
            }
        }
    }
}

The SwiftUI view example above contains a function that creates rows (technically a VStack with a Divider and an HStack inside), and each HStack contains two texts separated by a Spacer, one of which is bolded.

The main view contains a stepper to control the digit numbers, with an onChange modifier to limit the number between 0 ~ 16 digits. The getRow function is called three times to create three rows: The first row shows the unformatted string interpolation of the math π (Double.pi), and the second and third rows show the value returned by the functions above inside a Text View.

In conclusion, formatting decimal places in Swift is easy and can be done using 2 methods, including string interpolation, and NSNumber Formatter. Depending on your needs, you can choose the method that works best for you.