-1

I have the following requirement

Textfield should restrict the decimal point to 2 values. if the user input the numbers with out any "." then the text field should format the values to like this

e.g. TYPING THIS -> LEADS TO THIS AMOUNT

27 -> 0.27

2765 -> 27.65

Also if the user input "." in the text field then it should format like this

0.27 ->0.27

27.65 ->27.65

27.6 ->27.60

Thanks

nickypatson
  • 146
  • 2
  • 13

1 Answers1

2

Here, I did the hard work for you. This is not exactly what you asked for, but it's a good starting point. Next time provide details of what is your problem and how you tried to solve it yourself (what did not work, what worked, etc.) and not just ask for the solution...


let inputs = ["2356", "232", "23.32", "00000.20"]

func removeDotsAndLeadingZeros(_ string: String) -> String {
    return string
        .replacingOccurrences(of: ".", with: "")
        .replacingOccurrences(of: "^0*", with: "", options: .regularExpression)
}

func format(_ number: Double) -> String {
    return String(format: "%.2f", number)
}

let noDots = inputs.map(removeDotsAndLeadingZeros)
let doubles = noDots.map { Double($0)! / 100 }
let formatted = doubles.map(format)

// prints ["23.56", "2.32", "23.32", "0.20"]
print(formatted)
Tomas Jablonskis
  • 4,246
  • 4
  • 22
  • 40