0

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
  }
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
oscar
  • 101
  • 1
  • 1
  • 7
  • Does this answer your question? [Rounding a double value to x number of decimal places in swift](https://stackoverflow.com/questions/27338573/rounding-a-double-value-to-x-number-of-decimal-places-in-swift) – Joakim Danielson Jan 24 '20 at 11:52
  • Unfortunately no, looked there all day.. – oscar Jan 24 '20 at 12:02
  • **And i don't want to convert it into a string and then format it because numbers like 600000000 are then unreadable.** 600000000 is an Integer. If you give 600000000.00 then it will work for sure. – Keshu R. Jan 24 '20 at 12:15
  • `but xcode won't let me do that` - what do you mean by that? – Cristik Jan 24 '20 at 12:19
  • sorry if i was unclear, it gives 600000000.0000000 right now – oscar Jan 24 '20 at 12:34
  • 1
    If that link doesn't help then you need to clarify what you are asking – Joakim Danielson Jan 24 '20 at 12:34
  • I have around 5 sliders (doubles) which then are calculated together for an output. This output gives a lot of decimals. – oscar Jan 24 '20 at 16:00
  • As mentioned in Joakim's link/comment, always round first then format & recast to string. – P2000 Jan 24 '20 at 20:15

3 Answers3

1

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
Rob C
  • 4,877
  • 1
  • 11
  • 24
1
let b: Double = Double(600000000.376)
let result = Double(round(100*b)/100)
print(result) // prints 600000000.38
Suresh Vutukuru
  • 211
  • 2
  • 8
0

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

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

should be only

pris, specifier: "%.2f")

oscar
  • 101
  • 1
  • 1
  • 7