I\'m printing out a number whose value I don\'t know. In most cases the number is whole or has a trailing .5. In some cases the number ends in .25 or .75, and very rarely th
If you want to print a floating point number to 3 decimal places, you can use String(format: "%.3f")
. This will round, so 0.10000001
becomes 0.100
, 0.1009
becomes 0.101
etc.
But it sounds like you don’t want the trailing zeros, so you might want to trim them off. (is there a way to do this with format
? edit: yes, g
as @simons points out)
Finally, this really shouldn’t be a class function since it’s operating on primitive types. Better to either make it a free function, or perhaps extend Double
/Float
:
extension Double {
func toString(#decimalPlaces: Int)->String {
return String(format: "%.\(decimalPlaces)g", self)
}
}
let number = -0.3009
number.toString(decimalPlaces: 3) // -0.301