Brewski Brewski - 3 months ago 15
iOS Question

Remove empty decimal with .droplast() in swift 3

I'm trying to remove empty trailing decimals and instead of using an extension for float I want to consider using droplast() if the result has any trailing zeros:

if result.contains(".0") {

if result.contains(".00") {

This does not seem to work and I get the warning:

Result of call to 'droplast()' is unused


Alternative solution using regular expression, the number of decimal places doesn't matter:

var result = "1.00"
result = result.replacingOccurrences(of: "\\.0+$", 
                          with: "", 
                       options: .regularExpression, 
                         range: result.startIndex..<result.endIndex)

Considering the entire string you can even omit the range parameter:

result = result.replacingOccurrences(of: "\\.0+$", 
                          with: "", 
                       options: .regularExpression)