-1

I have a text return value of "3.5". I would need to format it to show "3.50"..

How do I do this?

It is all in strings as the value is extracted from a textfield

thanks

Steve Law
  • 13
  • 1

2 Answers2

2

You can just print with a String initializer

if let value = Double(stringValue) {
    print("I want two precision point for \(value) to be \(String(format: "%.2f", value))")
}

It will output to I want two precision point for 3.5 to be 3.50\n

Happiehappie
  • 1,084
  • 2
  • 13
  • 26
  • The OP has a string, not a number. – rmaddy Jul 14 '16 at 04:13
  • Thanks mate.. I guess I need to know what ""%.2f"" reference too. Where can I get this reference.. let me guess, Apple Developer ref? – Steve Law Jul 14 '16 at 16:26
  • https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html – Happiehappie Jul 15 '16 at 01:17
  • There you go. It's more like a programming thing though, than an iOS/Swift thing, the 2 stands for positional specifier, so if you want to print out 3.500, just replace .2f to .3f. the 'f' there just means that it's a floating point number. – Happiehappie Jul 15 '16 at 01:18
  • Do accept the answer if this is indeed what you wanted. – Happiehappie Jul 15 '16 at 09:05
0

You can use the 'NSNumberFormatter' to format the amount values as given below:

let currencyFormatter: NSNumberFormatter = {
    let currencyFormatter = NSNumberFormatter()
    currencyFormatter.locale = NSLocale(localeIdentifier: "en")
    currencyFormatter.numberStyle = .CurrencyStyle
    return currencyFormatter
}()

func formattedStringForAmount(amount: String) -> String {
    return currencyFormatter.stringFromNumber(Double(amount)!)!
}
Arasuvel
  • 2,971
  • 1
  • 25
  • 40