user3723418
user3723418

Reputation:

Swift String Manipulation

I have converted a double to a string as I think it would be easier to manipulate. I have a string of: 14.52637472 for example.

How can I split it up into 2 variables, one for before the period, and one for ONLY 2 DECIMALS after?

so it should be: one = 14 and two = 52

This is my code to convert into a string: var str: String = all.bridgeToObjectiveC().stringValue

I don't know objective C, so I wouldn't really be able to do it that way, and I have read over the swift book on strings, but it does not discuss how to do this, or atleast I could not find that part?

Please would you help me out, want to build the app for my father to surprise him.

Upvotes: 2

Views: 1599

Answers (1)

Mick MacCallum
Mick MacCallum

Reputation: 130193

Start with the double, use NSString's format: initializer coupled with a format specifier to trim all but the tenths and hundredths column, and convert to string. Then use NSString's componentsSeparatedByString() to create a list of items separated by the period.

let theNumber = 14.52637472
let theString = NSString(format: "%.2f", theNumber)
let theList = theString.componentsSeparatedByString(".")

let left = theList[0] as String  // Outputs 14
let right = theList[1] as String // Outputs 53

As second option using NSNumberFormatter.

let decimalNumber = NSDecimalNumber(double: 14.52637472)

let numberFormatter = NSNumberFormatter()
numberFormatter.maximumIntegerDigits = 2
numberFormatter.maximumFractionDigits = 2

let stringValue = numberFormatter.stringFromNumber(decimalNumber)
let theList = stringValue.componentsSeparatedByString(".")

Upvotes: 1

Related Questions