Round up double to 2 decimal places

SwiftDouble

Swift Problem Overview


How do I round up currentRatio to two decimal places?

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

Swift Solutions


Solution 1 - Swift

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"

Solution 2 - Swift

(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"
}

Solution 3 - Swift

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 

Solution 4 - Swift

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

Solution 5 - Swift

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"

Solution 6 - Swift

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.

Solution 7 - Swift

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.

Solution 8 - Swift

@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

Solution 9 - Swift

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

Output: 34.58

Solution 10 - Swift

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

Solution 11 - Swift

Try this , you will get a better result instead of 0.0

extension Double {
    func rounded(toPlaces places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
    func toRoundedString(toPlaces places:Int) -> String {
        let amount = self.rounded(toPlaces: places)
        let str_mount = String(amount)
        
        let sub_amountStrings = str_mount.split(separator: ".")
        
        if sub_amountStrings.count == 1
        {
          var re_str = "\(sub_amountStrings[0])."
            for _ in 0..<places
            {
                re_str += "0"
            }
            return re_str
         
        }
        else if sub_amountStrings.count > 1, "\(sub_amountStrings[1])".count < places
        {
            var re_str = "\(sub_amountStrings[0]).\(sub_amountStrings[1])"
            let tem_places = (places -  "\(sub_amountStrings[1])".count)
              for _ in 0..<tem_places
              {
                  re_str += "0"
              }
            return re_str
        }
        
        return str_mount
    }
}

Solution 12 - Swift

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

Solution 13 - Swift

Just single line of code:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDel HindsView Question on Stackoverflow
Solution 1 - SwiftJALView Answer on Stackoverflow
Solution 2 - SwiftMehulView Answer on Stackoverflow
Solution 3 - SwiftChetan RajagiriView Answer on Stackoverflow
Solution 4 - SwiftMichael YagudaevView Answer on Stackoverflow
Solution 5 - SwiftgargView Answer on Stackoverflow
Solution 6 - SwiftMerichleView Answer on Stackoverflow
Solution 7 - SwiftDave YView Answer on Stackoverflow
Solution 8 - SwiftAbhijithView Answer on Stackoverflow
Solution 9 - SwiftShobhit CView Answer on Stackoverflow
Solution 10 - SwiftJoannesView Answer on Stackoverflow
Solution 11 - Swiftuser17611533View Answer on Stackoverflow
Solution 12 - SwiftAkbar KhanView Answer on Stackoverflow
Solution 13 - SwiftMr.Javed MultaniView Answer on Stackoverflow