Round up double to 2 decimal places
Use a format string to round up to two decimal places and convert the double
to a String
:
let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)!
railRatioLabelField.text! = String(format: "%.2f", currentRatio)
Example:
let myDouble = 3.141
let doubleStr = String(format: "%.2f", myDouble) // "3.14"
If you want to round up your last decimal place, you could do something like this (thanks Phoen1xUK):
let myDouble = 3.141
let doubleStr = String(format: "%.2f", ceil(myDouble*100)/100) // "3.15"
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
(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"
}