If you want to print a floating point number up to three decimal places, you can use String(format: "%.3f") . This will be rounded, so 0.10000001 will become 0.100 , 0.1009 will become 0.101 , etc.
But it sounds like you don't want trailing zeros, so you can trim them. (is there a way to do this with format ? edit: yes, g as @simons points out)
Finally, this really should not be a class function, since it works on primitive types. Itβs better to either make it a free function or expand Double / Float :
extension Double { func toString(#decimalPlaces: Int)->String { return String(format: "%.\(decimalPlaces)g", self) } } let number = -0.3009 number.toString(decimalPlaces: 3)
Airspeed velocity
source share