Formatting decimal places with unknown number

后端 未结 4 1449
青春惊慌失措
青春惊慌失措 2020-12-04 02:29

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

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 03:03

    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
    

提交回复
热议问题