How to round Double values?

Asked

Viewed 1,491 times

3

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 have this result, I think there must be a way without having to use the class String.

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

3 answers

3


  • 1

    Thanks @bigown, I haven’t had time for all of your SOP responses but I did a read on Nsnumberformatter, my intention is to really learn more about the language and not be programming by the wayside.

1

In Swift we can create Extensions (which is similar to the Categories of Objective-C), so we can add a new functionality to the 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
  • I didn’t know Extensions @iTsangar, I mixed your answer with that of mustache and I am editing in your reply, feel free to make the necessary changes. Thank you for the reply

  • @Fábioreibnitz recommend you create a new answer with the editions you made in my reply, so it gets more organized.

  • 2

    ok @iTsangar , I think it is more appropriate to use the Nsnumberformatter, allows later to make further modifications if necessary. Thanks again for the help

1

After the replies of @Maniero and @iTSanguar I made a function that uses part of the concepts presented by them and also me for this that I found in ONLY

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
  • But you said you didn’t want to go rogue :)

  • @bigown hahaha, and I thought it was going well.. what would you advise me? take off Extension? take away the function of Extension?

  • Torar the Double. If you keep using a guy who can’t guarantee the accuracy of the values, you’re going to have problems. That’s why I told you to read everything. The floating point type cannot represent all possible decimal values, so these rounding devices do not work. Because I have no way to execute Swift, otherwise I would show you that some numbers will work, some numbers won’t. Now, if you don’t care about accuracy, then you can use it. Some types of use, accuracy is not important. But don’t expect it to keep the number of decimals.

  • @bigwon started when it was passing functions from excel to Swift and the values were different.. things of 0.0001 then I started to try to force a rounding.. but later I saw that the error was elsewhere.. and no more rounding. but as I had already done the gambiarra, I wanted to put in discussion, I really did not have time to read everything, but what caught my attention, it was that in these forms presented it makes the rounding.. that in many cases is important.. for example.. student was with average 6.78 he rounds to 7

  • Are you describing the problem of double. I told you what actually happens, if you want to trust the coincidence, that’s up to you. All good programmers know how to do it right and guaranteed.

  • I will continue searching the links you suggested and see if I can find the best solution, I confess that I still have to read the Nsdecimalnumber and more other links.. because the gut is big hehe. Thanks again!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.