Cannot convert value of type in extension

Hello folks, I'm currently trying to understand extensions and I'm looking for solution how to convert pow() inside my Double's extension.

import Foundation

extension Double {
    func rounded(to places: Int) -> Double {
        let precisionNumber = pow(10, places)
        var value = self
        value *= precisionNumber
        value.round()
        value /= precisionNumber
        return value
    }
}

var myDouble = 3.14159
print(myDouble.rounded(to: 2))

When I'm trying to multiply or divide "value" there is an error, because of their different types. pow() function imposes Decimal type on me. Is there any solution or better way to do this?

Regards, misty

Accepted Reply

or let precisionNumber = (pow(10, places) as NSDecimalNumber).doubleValue

Replies

Xcode's compiler should provide a fix for you if you click the button for the error in the source code editor and click the Fix button.

The fix is to create a Double value from the precisionNumber constant to use for multiplying and dividing.

value *= Double(precisionNumber)
value /= Double(precisionNumber)
  • It doesn't work inside Double struct, but the solution was even simpler. I just used:

    let precisionNumber = pow(10, Double(places))

Add a Comment

or let precisionNumber = (pow(10, places) as NSDecimalNumber).doubleValue