Saturday, 11 May 2019

Local Currency TextField

Goal

To have a TextField display as currency in the users local currency, and update as the user types.

Gif

Initial setup

  • New project.
  • Add a TextView.
  • Add a method to the TextView named "formatAsCurrency", it should take one parameter "text", which will be of type String : formatAsCurrency(text)
  • Add a property to the TextView named "formatter"
  • Set the TextView's keyboard style to NumberPad in the TextVievs settings.
  • Check "End on return" and "Clears on editing" checkboxes in the TextVievs settings

Our method

  • 1 : Add this code inside the Changed event of TextView1 :
self.formatAsCurrency(self.text)

return true

  • 2 : Add this code to the Load event of TextView1 :
var formatter:NumberFormatter = NumberFormatter()
formatter.locale = Locale.system()
if(formatter.locale.currencyCode == null){
	formatter.locale = Locale("en_US") // Default Local Fallback
}
formatter.numberStyle = NumberFormatterStyle.Currency
self.formatter = formatter

self.text = self.formatter.stringFromNumber(00000)

  • 3 : Add this code to the DidEndEditing event of TextView1 :
if(self.text.length == 0  or self.text == ""  or self.text == null){
	self.text = self.formatter.stringFromNumber(00000)
}

  • 4 : Add this code to the formatAsCurrency method you created in TextView1 :
var currencySymbol:String = self.formatter.currencySymbol
var groupingSeparator:String = self.formatter.groupingSeparator
var decimalSeparator = self.formatter.decimalSeparator

var newText:String = text
newText = newText.replace(currencySymbol,"")
newText = newText.replace(groupingSeparator,"")
newText = newText.replace(decimalSeparator,"")

var tempText = newText
for (var x in tempText){
	if(x == 0 && newText.length > 1){
		newText = newText[1...-1]
	}else{
		break
	}
}

var newValue:Float = newText.number()

var divisor:Float = 1.0

if(newText.length == 0  or newValue == 0){
	self.text = null
}else if(newText.length > self.formatter.maximumSignificantDigits + 2){
	self.text = self.text
}else{
	if(self.formatter.maximumFractionDigits == 2){
		divisor = 100.0
	}else if(self.formatter.maximumFractionDigits == 3){
		divisor = 1000.0
	}
	var newAmount:Float = newValue / divisor
	self.text = self.formatter.stringFromNumber(newAmount)
}

That's it!

Your done. Enjoy.

Download completed project file

Currency Field Project File.

.

No comments:

Post a Comment

isDarkColor() Is it?

The Goal To decide what colour text to place on an unknown background color. In this example of using the function isDarkColor(), we switch ...