Round a digit upto two decimal place in Swift
If you want to really round the number, and not just format it as rounded for display purposes, then I prefer something a little more general-purpose:
extension Double {
func rounded(digits: Int) -> Double {
let multiplier = pow(10.0, Double(digits))
return (self * multiplier).rounded() / multiplier
}
}
So you can then do something like:
let foo = 3.14159.rounded(digits: 3) // 3.142
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 = Double(String(format: "%.2f", myDouble)) // 3.14
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 :
let myDouble = 3.141
let doubleStr = Double(String(format: "%.2f", ceil(myDouble*100)/100)) // 3.15
let myDouble = 3.141
let doubleStr = String(format: "%.2f", ceil(myDouble*100)/100) // "3.15"