Stay with 2 decimals Swift Xcode

0

I consume a service "x" which gives me the balance of the accounts

for example em will return 98675.38282761

What I need is to stay alone with 2 decimals, I currently get the balance and I show it in a label as follows:

let balanceNumber = (messageRS["balance"] as? NSNumber)!
                        var balance = balanceNumber.stringValue
                        if(balance.isEmpty){
                            balance = (messageRS["availableBalance"] as? String)!
                        }
                        if(!balance.isEmpty){
                            self.strLblAccountBalance.text = newBalanceMsg.replacingOccurrences(of: "/(balance)/", with: balance)
                        }else{
                            self.strLblAccountBalance.text = newBalanceMsg.replacingOccurrences(of: "/(balance)/", with: "---")
                        }

How could I just print the number with 2 decimals

    
asked by Bruno Sosa Fast Tag 11.08.2018 в 19:01
source

3 answers

1

You can use NSDecimalNumber which also allows you to round up.

var number: NSDecimalNumber = 12334445.4567721
    let behavior = NSDecimalNumberHandler(roundingMode: .plain, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true)
    number = number.rounding(accordingToBehavior: behavior)

    print(number) // 12334445.46
    
answered by 27.09.2018 в 15:26
0

Resolved as follows

 let balanceNumber = (messageRS["balance"] as? Double)!
 var balance = String(format: "%.2f", balanceNumber)
    
answered by 11.08.2018 в 19:12
0

You can add this extension

public extension FloatingPoint {
    /// Rounds the double to decimal places value
    func rounded(toPlaces places: Int) -> Self {
        let divisor = Self(Int(pow(10.0, Double(places))))
        return (self * divisor).rounded() / divisor
    }
}

balanceNumber.rounded(toPlaces: 2)
    
answered by 29.08.2018 в 22:34