Search code examples
iosswiftdoubletrailing

Swift - Remove Trailing Zeros From Double


What is the function that removes trailing zeros from doubles?

var double = 3.0
var double2 = 3.10

println(func(double)) // 3
println(func(double2)) // 3.1

Solution

  • In Swift 4 you can do it like that:

    extension Double {
        func removeZerosFromEnd() -> String {
            let formatter = NumberFormatter()
            let number = NSNumber(value: self)
            formatter.minimumFractionDigits = 0
            formatter.maximumFractionDigits = 16 //maximum digits in Double after dot (maximum precision)
            return String(formatter.string(from: number) ?? "")
        }
    }
    

    example of use: print (Double("128834.567891000").removeZerosFromEnd()) result: 128834.567891

    You can also count how many decimal digits has your string:

    import Foundation
    
    extension Double {
        func removeZerosFromEnd() -> String {
            let formatter = NumberFormatter()
            let number = NSNumber(value: self)
            formatter.minimumFractionDigits = 0
            formatter.maximumFractionDigits = (self.components(separatedBy: ".").last)!.count
            return String(formatter.string(from: number) ?? "")
        }
    }