How to round values of type Double?

2

I made a function to return the rounding of values of type Double , the function is working, but I do not know if it is the ideal way to get this result, I think there must be a way without having to use the String class.

var numero: Double = 6.73865

func arredonda(valor: Double, casasdecimais: Int)-> Double{
    let formato = String(casasdecimais)+"f"
    return Double(String(format: "%."+formato, valor))!
}

arredonda(numero, casasdecimais:  3)  

// returns 6,739

arredonda(numero, casasdecimais:  2) 

// returns 6.74

    
asked by anonymous 18.11.2015 / 13:58

3 answers

3

There is no way to have control over decimal places in a number of type double , this is characteristic of it. If you need this, you need to use another type of data. This would be the NSDecimalNumber . Also useful is the class NSNumberFormatter

Read more about this in answer about Objective C . And continue following all links to understand why this occurs.

    
18.11.2015 / 14:08
1

In Swift we can create Extensions (which is similar with Objective-C Categories , then we can add a new feature for class Double :

extension Double {
    /// Arredonda um Double conforme quantidade de casas decimais
    func arredonda(casas: Int) -> Double {
        let divisor = pow(10.0, Double(casas))
        return round(self * divisor) / divisor
    }
}


let a = Double(0.123456789).arredonda(4)  //0.1235
let b = Double(0.123456789).arredonda(5)  //0.12346
let c = Double(6.73865).arredonda(3)  //6.739
let d = Double(6.73865).arredonda(2)  //6.74
    
18.11.2015 / 14:44
1

After the responses from @bigown and @iTSanguar I made a function that uses some of the concepts presented by them and also me by this one I found in SO

extension Double {
        /// Arredonda um Double conforme quantidade de casas decimais
        func arredonda(casasDecimais: Int) -> Double {
            var formatacao:String {
                let formatacao = NSNumberFormatter()
                formatacao.minimumFractionDigits = casasDecimais
                return formatacao.stringFromNumber(self)!

        }
        return Double(formatacao)!

    }
}
var numero: Double  = 6.73865
numero.arredonda(3) // 6.739
numero.arredonda(2) // 6.74
    
18.11.2015 / 17:01