Rounding a double value to x number of decimal places in swift

前端 未结 28 2536
日久生厌
日久生厌 2020-11-22 06:11

Can anyone tell me how to round a double value to x number of decimal places in Swift?

I have:

var totalWorkTimeInHours = (totalWorkTime/60/60)


        
相关标签:
28条回答
  • 2020-11-22 06:36

    You can add this extension :

    extension Double {
        var clean: String {
            return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(format: "%.2f", self)
        }
    }
    

    and call it like this :

    let ex: Double = 10.123546789
    print(ex.clean) // 10.12
    
    0 讨论(0)
  • 2020-11-22 06:36
    //find the distance between two points
    let coordinateSource = CLLocation(latitude: 30.7717625, longitude:76.5741449 )
    let coordinateDestination = CLLocation(latitude: 29.9810859, longitude: 76.5663599)
    let distanceInMeters = coordinateSource.distance(from: coordinateDestination)
    let valueInKms = distanceInMeters/1000
    let preciseValueUptoThreeDigit = Double(round(1000*valueInKms)/1000)
    self.lblTotalDistance.text = "Distance is : \(preciseValueUptoThreeDigit) kms"
    
    0 讨论(0)
  • 2020-11-22 06:37

    This is a fully worked code

    Swift 3.0/4.0/5.0 , Xcode 9.0 GM/9.2 and above

    let doubleValue : Double = 123.32565254455
    self.lblValue.text = String(format:"%.f", doubleValue)
    print(self.lblValue.text)
    

    output - 123

    let doubleValue : Double = 123.32565254455
    self.lblValue_1.text = String(format:"%.1f", doubleValue)
    print(self.lblValue_1.text)
    

    output - 123.3

    let doubleValue : Double = 123.32565254455
    self.lblValue_2.text = String(format:"%.2f", doubleValue)
    print(self.lblValue_2.text)
    

    output - 123.33

    let doubleValue : Double = 123.32565254455
    self.lblValue_3.text = String(format:"%.3f", doubleValue)
    print(self.lblValue_3.text)
    

    output - 123.326

    0 讨论(0)
  • 2020-11-22 06:37

    I would use

    print(String(format: "%.3f", totalWorkTimeInHours))
    

    and change .3f to any number of decimal numbers you need

    0 讨论(0)
  • 2020-11-22 06:37

    round a double value to x number of decimal
    NO. of digits after decimal

    var x = 1.5657676754
    var y = (x*10000).rounded()/10000
    print(y)  // 1.5658 
    

    var x = 1.5657676754 
    var y = (x*100).rounded()/100
    print(y)  // 1.57 
    

    var x = 1.5657676754
    var y = (x*10).rounded()/10
    print(y)  // 1.6
    
    0 讨论(0)
  • 2020-11-22 06:37

    I found this wondering if it is possible to correct a user's input. That is if they enter three decimals instead of two for a dollar amount. Say 1.111 instead of 1.11 can you fix it by rounding? The answer for many reasons is no! With money anything over i.e. 0.001 would eventually cause problems in a real checkbook.

    Here is a function to check the users input for too many values after the period. But which will allow 1., 1.1 and 1.11.

    It is assumed that the value has already been checked for successful conversion from a String to a Double.

    //func need to be where transactionAmount.text is in scope
    
    func checkDoublesForOnlyTwoDecimalsOrLess()->Bool{
    
    
        var theTransactionCharacterMinusThree: Character = "A"
        var theTransactionCharacterMinusTwo: Character = "A"
        var theTransactionCharacterMinusOne: Character = "A"
    
        var result = false
    
        var periodCharacter:Character = "."
    
    
        var myCopyString = transactionAmount.text!
    
        if myCopyString.containsString(".") {
    
             if( myCopyString.characters.count >= 3){
                            theTransactionCharacterMinusThree = myCopyString[myCopyString.endIndex.advancedBy(-3)]
             }
    
            if( myCopyString.characters.count >= 2){
                theTransactionCharacterMinusTwo = myCopyString[myCopyString.endIndex.advancedBy(-2)]
            }
    
            if( myCopyString.characters.count > 1){
                theTransactionCharacterMinusOne = myCopyString[myCopyString.endIndex.advancedBy(-1)]
            }
    
    
              if  theTransactionCharacterMinusThree  == periodCharacter {
    
                                result = true
              }
    
    
            if theTransactionCharacterMinusTwo == periodCharacter {
    
                result = true
            }
    
    
    
            if theTransactionCharacterMinusOne == periodCharacter {
    
                result = true
            }
    
        }else {
    
            //if there is no period and it is a valid double it is good          
            result = true
    
        }
    
        return result
    
    
    }
    
    0 讨论(0)
提交回复
热议问题