How to remove trailing zeros from a string in Swift

1 Answer

0 votes
import Foundation

func removeTrailingZeros(_ str: String) -> String {
    var result = str
    
    while result.hasSuffix("0") {
        result = String(result.dropLast())
    }

    if result.hasSuffix(".") {
        result = String(result.dropLast())
    }

    return result
}

var str = "457833.8591000"

str = removeTrailingZeros(str)

print(str)



/*
run:
 
457833.8591
 
*/

 



answered Nov 15, 2024 by avibootz
edited Nov 17, 2024 by avibootz

Related questions

3 answers 131 views
1 answer 148 views
1 answer 108 views
1 answer 83 views
...