[swift] Round up double to 2 decimal places

How do I round up currentRatio to two decimal places?

let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)!
railRatioLabelField.text! = "\(currentRatio)"

This question is related to swift double

The answer is


Consider using NumberFormatter for this purpose, it provides more flexibility if you want to print the percentage sign of the ratio or if you have things like currency and large numbers.

let amount = 10.000001
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
let formattedAmount = formatter.string(from: amount as NSNumber)! 
print(formattedAmount) // 10

The code for specific digits after decimals is:

var roundedString = String(format: "%.2f", currentRatio)

Here the %.2f tells the swift to make this number rounded to 2 decimal places.


@Rounded, A swift 5.1 property wrapper Example :

struct GameResult {
    @Rounded(rule: NSDecimalNumber.RoundingMode.up,scale: 4)
    var score: Decimal
}

var result = GameResult()
result.score = 3.14159265358979
print(result.score) // 3.1416

if you give it 234.545332233 it will give you 234.54

let textData = Double(myTextField.text!)!
let text = String(format: "%.2f", arguments: [textData])
mylabel.text = text

Adding to above answer if we want to format Double multiple times, we can use protocol extension of Double like below:

extension Double {
    var dollarString:String {
        return String(format: "$%.2f", self)
    }
}

let a = 45.666

print(a.dollarString) //will print "$45.67"

(Swift 4.2 Xcode 11) Simple to use Extension:-

extension Double {
    func round(to places: Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
}

Use:-

if let distanceDb = Double(strDistance) {
   cell.lblDistance.text = "\(distanceDb.round(to:2)) km"
}

Updated to SWIFT 4 and the proper answer for the question

If you want to round up to 2 decimal places you should multiply with 100 then round it off and then divide by 100

var x = 1.5657676754 
var y = (x*100).rounded()/100
print(y)  // 1.57 

Just single line of code:

 let obj = self.arrayResult[indexPath.row]
 let str = String(format: "%.2f", arguments: [Double((obj.mainWeight)!)!])

String(format: "%.2f", Double(round(1000*34.578)/1000))

Output: 34.58


Just a quick follow-up answer for noobs like me:

You can make the other answers super easily implementable by using a function with an output. E.g.

  func twoDecimals(number: Float) -> String{
    return String(format: "%.2f", number)
}

This way, whenever you want to grab a value to 2 decimal places you just type

twoDecimals('Your number here')

...

Simples!

P.s. You could also make it return a Float value, or anything you want, by then converting it again after the String conversion as follows:

 func twoDecimals(number: Float) -> Float{
    let stringValue = String(format: "%.2f", number)
    return Float(stringValue)!
}

Hope that helps.