0

So I have a Double that gets calculated and varies in length each time (based on certain input). This Double is placed in to a String.

var doubleNumber = 30440.8734
var string = "€ \(round(100 * doubleNumber) / 100)"

var numberString: String = string.stringByReplacingOccurrencesOfString("€ ", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
var splitString = split(numberString) {$0 == "."}
println(splitString[0])

Result would be: "30440"

What I would like to do is to place spaces in this number for readability. For which the result would end in: "30 440"

Any suggestions?

Swifting
  • 449
  • 1
  • 5
  • 19
  • 3
    Read the Apple documentation: [Number Formatters](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfNumberFormatting10_4.html). NSNumberFormatter is your friend. There are also *many* examples here on SO. – Martin R Mar 05 '15 at 13:13
  • possible duplicate of [Struggling with NSNumberFormatter in Swift for currency](http://stackoverflow.com/questions/24960621/struggling-with-nsnumberformatter-in-swift-for-currency) – sbooth Mar 05 '15 at 13:42
  • Not a duplicate, I don't want the number to be specific to the users location. I want to add in a space after each 3 characters from the right. – Swifting Mar 05 '15 at 13:48

2 Answers2

0

Regardless of the issue of currency formats, you can use an NSNumberFormatter to add spaces as grouping separators in a number:

var doubleNumber = 30440.8734

let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = .CurrencyStyle
numberFormatter.currencySymbol = "€ "
numberFormatter.currencyGroupingSeparator = " "
numberFormatter.maximumFractionDigits = 0
if let formattedString = numberFormatter.stringFromNumber(doubleNumber) {
    println(formattedString)
}

Output: € 30 441

James Frost
  • 6,960
  • 1
  • 33
  • 42
0

I do think that NSNumberFormatter approach is better:

let f = NSNumberFormatter()
f.groupingSeparator = " "
f.groupingSize = 3
f.usesGroupingSeparator = true
f.stringFromNumber("30456".toInt()!)

but here's my solution if I would do this task without formatter:

var i: Int = count(number)
let a = "".join(map(number) {String($0) + (--i % 3 == 0 ? " " : "")})

a.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
kovpas
  • 9,553
  • 6
  • 40
  • 44