Reputation: 684
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") {
result.characters.dropLast()
}
if result.contains(".00") {
result.characters.dropLast(2)
}
This does not seem to work and I get the warning:
Result of call to 'droplast()' is unused
Upvotes: 1
Views: 536
Reputation: 285092
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)
Upvotes: 3
Reputation: 9136
dropLast method will return a subsequence that leaves off the dropped items, so in this case it won't modify the result variable, then you would need to create a new String based on the result of dropLast method call and assign it to result variable.
var result: String = "1.00"
var dropCount = getTrailingDecimalCount(from: result)
print(dropCount) // outputs 2
if let dropCount = dropCount {
result = String(result.characters.dropLast(dropCount))
print(result) // outputs 1.
}
func getTrailingDecimalCount(from string: String) -> Int? {
var counter = 0
guard string.characters.contains(".") else {
return nil
}
for char in string.characters.reversed() {
if char == "." {
break
}
counter = counter + 1
}
return counter
}
Upvotes: 1