0

I have to show the price in the text of a label. public var balance: Float only as a number I get an "8000" instead it should show "80.00 €". I can't convert it can you give me a hand?

public var balance: Float
    saldoPrice.text = String(userDataByCode!.balance)

in this way I am shown "8000"

ste
  • 3
  • 3
  • 2
    You need to use a [NumberFormatter](https://developer.apple.com/documentation/foundation/numberformatter) and also divide your float with 100 it seems. There are several pre-defined [styles for currencies](https://developer.apple.com/documentation/foundation/numberformatter/style) – Joakim Danielson Feb 19 '21 at 11:15
  • You should use "Decimal" for the calculation. – Ten Feb 19 '21 at 11:38
  • You need to state your request and you can do it like this https://stackoverflow.com/questions/29999024/adding-thousand-separator-to-int-in-swift – Ten Feb 19 '21 at 11:39

1 Answers1

0

I created the following extension that solves your specific problem:

extension Double{
     func formatToAmount() -> String{
        let numberFormatter = NumberFormatter()
        numberFormatter.groupingSeparator = ","
        numberFormatter.groupingSize = 3
        numberFormatter.usesGroupingSeparator = true
        numberFormatter.decimalSeparator = "."
        numberFormatter.numberStyle = .decimal
        numberFormatter.maximumFractionDigits = 2
        
        let value = self.roundToDecimal(2)
        
        var res = numberFormatter.string(from: value as NSNumber)!
        if !res.contains("."){
            res += ".00"
        }else{
            let resAfterComma = String(res.split(separator: ".")[1])
            if resAfterComma.count == 1{  res += "0" }
        }
        res += " €"
        return res
    }

    func roundToDecimal(_ fractionDigits: Int) -> Double {
        let multiplier = pow(10, Double(fractionDigits))
        return Darwin.round(self * multiplier) / multiplier
    }
}

Usage:

var yourNumber : Double = 80
yourNumber.formatToAmount() // prints: 80.00 €
Donat Kabashi
  • 384
  • 4
  • 10