Swift 5: Format Float Number for zero negative number

244 Views Asked by At

I want to format a negative number and be left with only two decimal places. But when the number is a negative -0.00 I want it to be unsigned. For example:

let negativeNumber = -0.008

let result = 0.00 

I try do this with numberFormatter but i get this result -0.00, and i want this result 0.00

This is the formatter i use:

 static func formatValue(_ value: Double, currency: Currency? = nil, options: [FormatterOption] = [], locale: Locale = Locale.current) -> String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.locale = locale

        let defaultOptions: [FormatterOption] = [.minFractionDigits(2),
                                                 .maxFractionDigits(currency?.decimals ?? 2),
                                                 .roundingMode(.down)]
        var completeDecimals = false

        for option in defaultOptions + options {
            switch option {
            case .minFractionDigits(let minValue):
                if let decimals = currency?.decimals, minValue > decimals {
                    continue
                }

                formatter.minimumFractionDigits = minValue

            case .maxFractionDigits(let maxValue):
                if let decimals = currency?.decimals, maxValue > decimals {
                    continue
                }

                formatter.maximumFractionDigits = maxValue

            case .roundingMode(let mode):
                formatter.roundingMode =

        }

        let formattedNumber = formatter.format(from: value)

        return formattedNumber
        
    }
0

There are 0 best solutions below