Search This Blog

Monday, October 10, 2016

iOS Swift. Rounding a double value to N number of decimal places

For round double values we can use classic algorithm of rounding. Add new function to Double class (with Extension):
import Foundation
import UIKit

extension Double {
    
    func roundToPlaces(places: Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
    
}

And we can use this extension for double variables:
let pi = 3.14159265
let roundedValue = pi.roundToPlaces(places: 2) // 3.14
print(roundedValue)

4 comments:

  1. Thank you so much for sharing your articles with us. Hopefully, you will be able to benefit us with more informative article.
    -Custom Website Design

    ReplyDelete
  2. This post wowed me with its well-researched content and excellent writing. Because I was so involved in this book, I couldn't put it down. Your work and ability have wowed me. Thank you very much. Those who want to learn more about it may find it useful. Best Custom Websites

    ReplyDelete
  3. Your article is unbelievable with precise knowledge. I can see a lot of research behind that and that is beyond my expectations.
    Create Your Own Website \

    ReplyDelete
  4. Great share!One of the best blogs I have Ever Seen. Keep going!
    Software Quality Experts

    ReplyDelete