Reputation: 870
I have TextField in my application, after entering value in textField i am checking textformat in following delegate method
func textFieldDidEndEditing(textField: UITextField)
I want to check like following,
if textField Containing "23" then output should be "23.00"
if textField Containing "23.1" then output should be "23.10"
if textField Containing "23.10" then output should be "23.10"
any idea for this
Upvotes: 0
Views: 84
Reputation: 285072
If it's guaranteed that the text is restricted to a numeric value I recommend NumberFormatter
let text = "23"
let numberFormatter = NumberFormatter()
numberFormatter.minimumFractionDigits = 2
let formattedString = numberFormatter.string(from: Double(text)! as NSNumber)
Sorry the code is Swift 3 code. It's highly recommended to update, consider that Swift 4 is waiting in the wings.
Upvotes: 3
Reputation: 6795
(Swift 3) It works good for the cases "23" , "23.1" , "23.10" .
func process(_ input : String ) -> String
{
var string = input
if !string.contains(".")
{
string += ".00"
}
else
{
for (index,char) in input.characters.enumerated()
{
if char == "."
{
if index == input.characters.count - 1
{
string += "00"
}
else if index == input.characters.count - 2
{
string += "0"
}
break;
}
}
}
return string
}
I hope can you handle issues between Swift 3 and Swift 2.3
Upvotes: 1