0

I have a problem, I need to round a double using the third digit after decimal point. Example: 16373.89732 -> because the number is 7( the third digit) It needs to became 16373.90. if it was < 5 nothing will need to happen, it will remain 16373.89.

let tempEndwert = ((1000*endwert).rounded())/1000 - I trie the but it is not working - 49263792.69752127 - this is the number. I need to save it formatted (49263792.70) - when rounded.

  • 1
    Try removing a 0. `let tempEndwert = ((100*endwert).rounded())/100` = `49263792.7` – Vollan Sep 11 '19 at 07:14
  • @Martin Kostadinov You are free to use the search box at the top to find similar topics to help yourself. – El Tomato Sep 11 '19 at 07:14
  • What is your desired output? A rounded double value that you need to use for further computation or is it a string that you will display or insert into some data like JSON? – Matic Oblak Sep 11 '19 at 07:15
  • 3
    Possible duplicate of [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) – Sagar Chauhan Sep 11 '19 at 07:15

3 Answers3

4

You can do this by

extension Formatter {
    static let number = NumberFormatter()
}

extension FloatingPoint {
    var asNumberString : String {
        Formatter.number.minimumFractionDigits = 2
        Formatter.number.maximumFractionDigits = 2
        Formatter.number.roundingMode = .halfEven
        Formatter.number.numberStyle = .decimal
        return Formatter.number.string(for: self) ?? ""
    }
}

Now You can test like

150.51581.asNumberString === > "150.52"
150.5141531.asNumberString === > "150.51"

Prashant Tukadiya
  • 15,838
  • 4
  • 62
  • 98
  • The same question with different answers can be found here https://stackoverflow.com/questions/24051314/precision-string-format-specifier-in-swift – NonCreature0714 Sep 11 '19 at 08:32
0

Convert the Double to String upto decimal places as per requirement. You can directly save String instead of Double, i.e.

let num = 16373.89732
let str = String(format: "%.2f", num)
print(str) //16373.90
PGDev
  • 23,751
  • 6
  • 34
  • 88
0
let number = 49263792.69752127
let numberRounded = String(format: "%.2f", (number * 100).rounded() / 100)

If you are trying to save your number as String the result will be "49263792.70"

However just by rounding it and store it somewhere as Double will result in storing 49263792.7

SwissMark
  • 1,041
  • 12
  • 21