Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift 3 String Extensions
import Foundation
extension String
{
/**
* Return formated currency string by locale with or not round
* @see https://developer.apple.com/documentation/foundation/numberformatter, https://developer.apple.com/documentation/foundation/numberformatter.style
* @return String if problem on format return string ""
*/
func toCurrency(localeItendifier: String = "pt_BR", withRound: Bool = false) -> String{
let numberFormatter: NumberFormatter = {
let formater = NumberFormatter()
formater.numberStyle = .currency
formater.locale = Locale(identifier: localeItendifier)
formater.alwaysShowsDecimalSeparator = true
formater.minimumFractionDigits = 2
formater.maximumFractionDigits = 2
return formater
}()
let valToFloat = Float(self)!
var val: NSNumber
if(withRound){
val = NSNumber(value: round(valToFloat))
} else {
val = NSNumber(value: valToFloat)
}
if let formmatedVal = numberFormatter.string(from: val){
return formmatedVal
}
return ""
}
/**
* Shortcut replacingOccurrences
* @return String - string replaced
*/
func replace(this: String, to: String) -> String
{
return self.replacingOccurrences(of: this, with: to)
}
/**
* Remove all another char did not match with characterset decimalDigits
* @see https://developer.apple.com/documentation/foundation/characterset
* @return String - String decimals
*/
func getDecimals() -> String
{
return components(separatedBy: CharacterSet.decimalDigits.inverted).joined()
}
/**
* Verify if char is a utf8 backspace, util for testin keyboard keypress
* @see https://developer.apple.com/documentation/swift/string/1641523-init
* @see https://developer.apple.com/documentation/kernel/1579329-strcmp
* @return Bool - if a backspace char return true else false
*/
func isBackSpace() -> Bool
{
let char = self.cString(using: String.Encoding.utf8)!
let isBackSpace = strcmp(char, "\\b")
if(isBackSpace == -92){ return true }
return false
}
}
@micheltlutz

This comment has been minimized.

Show comment
Hide comment
@micheltlutz

micheltlutz Aug 10, 2017

Usage
var compras = "R$1000.99"
var comprasnumero = "12300.92"

print(comprasnumero.toCurrency())
print(comprasnumero.toCurrency(localeItendifier: "pt_BR", withRound: true))

print(compras.replace(this: "R$", to: ""))
print(compras.getDecimals())
print(compras.isBackSpace())

Owner

micheltlutz commented Aug 10, 2017

Usage
var compras = "R$1000.99"
var comprasnumero = "12300.92"

print(comprasnumero.toCurrency())
print(comprasnumero.toCurrency(localeItendifier: "pt_BR", withRound: true))

print(compras.replace(this: "R$", to: ""))
print(compras.getDecimals())
print(compras.isBackSpace())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment