Swift - Remove Trailing Zeros From Double

Bogdan Bogdanov picture Bogdan Bogdanov · Apr 10, 2015 · Viewed 27.4k times · Source

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

Answer

Dharmesh Kheni picture Dharmesh Kheni · Apr 10, 2015

You can do it this way but it will return a string:

var double = 3.0
var double2 = 3.10

func forTrailingZero(temp: Double) -> String {
    var tempVar = String(format: "%g", temp)
    return tempVar
}

forTrailingZero(double)   //3
forTrailingZero(double2)  //3.1