Swift Remove trailing zeros

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.

Swift Remove Trailing Zeros #2


extension Double {
var removeZero:String {
let nf = NSNumberFormatter()
nf.minimumFractionDigits = 0
nf.maximumFractionDigits = 0
return nf.stringFromNumber(self)!
}
}

var newDouble = 1202.001

print(“\(newDouble.removeZero)”)

Swift remove trailing zeros #2 example is reusable. Extensions like this I often put in separate files too. And that way is very easy to use in other projects.

I have similar extension on my github account. You can check them out at github here: https://github.com/solron

You can also check out my YouTube account for swift videos. You can find my YouTube account here: https://www.youtube.com/user/solron75/videos

That is it for swift remove trailing zeros.

Enjoy!

Happy coding!

November 29th, 2015 by
Optimization WordPress Plugins & Solutions by W3 EDGE