Swift Remove trailing zeros

Swift Remove Trailing Zeros

In Swift remove trailing zeros is needed sometimes. When printing values, and I dont want any trailing zeros, but still need to do math with Double variables. I use two different methods of Swift removing trailing zeros. For quick and dirty solutions I just convert the Double or float to an Integer. Or copy the Double / Float to an integer variable. You can do that like this:

Swift Remove Trailing Zeros #1

var myDouble = 12.0 var myInt:Int = Int(myDouble)

print(“\(myInt)”)

This example copies the myDouble variable into myInt variable. For a quick solution in a small project, this is working just fine. Of course it will work just fine in any size project. And multiple times. But if it is needed to do more than a few times. It would be better to make an extension to Double I think.

Swift extensions can be made to extend functionality to datatypes. If my next example I use an extension to remove trailing zeros. Here it will return a string. The times I need to remove trailing zeros, is when I need to present the numbers. Within the code you should still just use the double / float variables. And calculate whatever you need to calculate.