oscar
oscar

Reputation: 111

Swift specify double without converting to string

I want to specify my (slider) double to 2 decimals but xcode won't let me do that:

return (Double(pris, specifier: "%.2f"))

And i don't want to convert it into a string and then format it because numbers like 600000000 are then unreadable.

I have tried solutions like :

extension Double {
// Rounds the double to 'places' significant digits
  func roundTo(places:Int) -> Double {
    guard self != 0.0 else {
        return 0
    }
    let divisor = pow(10.0, Double(places) - ceil(log10(fabs(self))))
    return (self * divisor).rounded() / divisor
  }
}

Upvotes: 0

Views: 109

Answers (3)

oscar
oscar

Reputation: 111

The simple solution was to remove the (Double) before the calculation.

return (Double(pris, specifier: "%.2f"))

should be only

pris, specifier: "%.2f")

Upvotes: 0

Rob C
Rob C

Reputation: 5073

This should do what you need:

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

print(10.125.roundedTo(places: 2)) // prints 10.13
print(10.124.roundedTo(places: 2)) // prints 10.12

Upvotes: 1

Suresh Vutukuru
Suresh Vutukuru

Reputation: 211

let b: Double = Double(600000000.376)
let result = Double(round(100*b)/100)
print(result) // prints 600000000.38

Upvotes: 1

Related Questions