2

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.

1 Answer 1

1

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(".")
Sign up to request clarification or add additional context in comments.

3 Comments

Worked! thanks so much! will accept answer as soon as the time is lifted
@user3723418 Glad to hear it. I've updated my post to include a second way of doing this if you're still interested.
It's worth noting that there's a bit of a code smell here: much of the manipulation that this very good answer suggests is using the number value as a number. That suggests you may not need to convert to string in the first place. Whether that's really the case depends on your requirements, of course.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.