94

How do I round up currentRatio to two decimal places?

let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)!
railRatioLabelField.text! = "\(currentRatio)"
JAL
  • 39,073
  • 22
  • 153
  • 285
Del Hinds
  • 2,257
  • 3
  • 9
  • 12
  • Do you want to just round `currentRatio` to two decimal places, or always round up? Ex: do you want 3.141 -> 3.14 or 3.141 -> 3.14? – JAL Jan 21 '16 at 17:28
  • Hi JAL, I want 3.149 to display as 3.15. However 3.141 should display 3.14. Thanks – Del Hinds Jan 21 '16 at 19:43
  • See the first part of my answer for the correct rounding. – JAL Jan 21 '16 at 19:48

12 Answers12

187

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"
JAL
  • 39,073
  • 22
  • 153
  • 285
  • Needs to be 3.15 if rounding up to two decimal places. – Matt Le Fleur Jan 21 '16 at 17:23
  • I thought the OP just wanted to round to two decimal places, rounding up or down as necessary. Just added a comment asking for clarification. – JAL Jan 21 '16 at 17:29
  • Hi Jal, Thank you, I used your answer which worked with a slight modification as follows:- _ = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)! railRatioLabelField.text! = String(format: "%.2f", currentRatio) – Del Hinds Jan 21 '16 at 19:50
  • 2
    This answers is to the question: "How to display Double with two digits in text label" or "... as string", this answer does not answer the question "Round up double to 2 decimal places" – mnl Oct 13 '17 at 16:14
  • @JAL i need olny .5 or 0 after point For ex. if we have 23.4 it should give 23.5 and if 23.8 it should 24.0 – guru Nov 13 '19 at 14:28
41

(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"
}
Mehul
  • 2,500
  • 18
  • 30
31

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 
Chetan Rajagiri
  • 820
  • 10
  • 13
  • 1
    Hi - I dont understand how you do your calculation in terms of returning a certain number of decimal. What if I want it to return 3 decimal place? – Sipho Koza May 17 '18 at 14:03
  • @SiphoKoza just multiply it by 1000 and then divide by 1000 – Chetan Rajagiri May 17 '18 at 15:55
  • This is not really the "proper" answer because internally, the number is saved in floating point, with is base 2, and you're trying to represent a base 10 number. For some numbers there is not an exact representation, and you'll wind up with too many digits when you go to print the value. The proper answer should return a string, not a Double or Float. – Victor Engel May 12 '19 at 00:09
  • @levan It works for zero too, just make sure it's a double – Chetan Rajagiri Jul 24 '19 at 07:35
  • You need to be careful with this approach. If you inspect the variable in the debugger you can see a different value (e.g. 1.569999999) even though it prints 1.57. If you need to round to 2 decimal places use a Decimal value type – Aggressor Jun 23 '20 at 12:33
  • 1
    Great answer, I think that this should be the accepted one. – אורי orihpt Oct 05 '20 at 22:45
15

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
Michael Yagudaev
  • 5,629
  • 2
  • 43
  • 50
13

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"
garg
  • 2,344
  • 20
  • 20
4

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.

Merichle
  • 586
  • 8
  • 12
4

@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
Abhijith
  • 2,264
  • 25
  • 28
3

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.

Dave Y
  • 185
  • 6
2
String(format: "%.2f", Double(round(1000*34.578)/1000))

Output: 34.58

Nisse Engström
  • 4,555
  • 22
  • 24
  • 38
Shobhit C
  • 808
  • 10
  • 14
0

Maybe also:

// Specify the decimal place to round to using an enum
public enum RoundingPrecision {
    case ones
    case tenths
    case hundredths
    case thousands
}

extension Double {
    // Round to the specific decimal place
    func customRound(_ rule: FloatingPointRoundingRule, precision: RoundingPrecision = .ones) -> Double {
        switch precision {
        case .ones: return (self * Double(1)).rounded(rule) / 1
        case .tenths: return (self * Double(10)).rounded(rule) / 10
        case .hundredths: return (self * Double(100)).rounded(rule) / 100
        case .thousands: return (self * Double(1000)).rounded(rule) / 1000
        }
    }
}

let value: Double = 98.163846
print(value.customRound(.toNearestOrEven, precision: .ones)) //98.0
print(value.customRound(.toNearestOrEven, precision: .tenths)) //98.2
print(value.customRound(.toNearestOrEven, precision: .hundredths)) //98.16
print(value.customRound(.toNearestOrEven, precision: .thousands)) //98.164

Keeps decimals, does not truncate but rounds

See for more details even specified rounding rules

Joannes
  • 1,616
  • 3
  • 11
  • 24
-2

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
Mohammad Kanan
  • 3,886
  • 10
  • 17
  • 37
Akbar Khan
  • 1,442
  • 13
  • 17
-6

Just single line of code:

 let obj = self.arrayResult[indexPath.row]
 let str = String(format: "%.2f", arguments: [Double((obj.mainWeight)!)!])
Mr.Javed Multani
  • 9,803
  • 2
  • 42
  • 45