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
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
In Swift 4 you can do it like that:
example of use:
print (Double("128834.567891000").removeZerosFromEnd())
result: 128834.567891You can also count how many decimal digits has your string:
You can do it this way but it will return a string:
Removing trailing zeros in output
This scenario is good when the default output precision is desired. We test the value for potential trailing zeros, and we use a different output format depending on it.
(works also with
extension Float
, but notFloat80
)Output:
Formatting with maximum fraction digits, without trailing zeros
This scenario is good when a custom output precision is desired. This solution seems roughly as fast as NumberFormatter + NSNumber solution from MirekE, but one benefit could be that we're avoiding NSObject here.
(works also with
extension Float
, but notFloat80
)Output for
maximumFractionDigits: 2
: