Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round up double to 2 decimal places

Tags:

double

swift

How do I round up currentRatio to two decimal places?

let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)! railRatioLabelField.text! = "\(currentRatio)" 
like image 451
Del Hinds Avatar asked Jan 21 '16 17:01

Del Hinds


People also ask

What does it mean to round up 2 decimal places?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.

What is 2.5 rounded 2 decimal?

Both 1.5 and 2.5 are rounded to 2 . 3.5 and 4.5 are rounded to 4 .


2 Answers

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" 
like image 133
JAL Avatar answered Oct 14 '22 09:10

JAL


(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" } 
like image 40
Mehul Avatar answered Oct 14 '22 10:10

Mehul