Formatting decimal places with unknown number

后端 未结 4 1452
青春惊慌失措
青春惊慌失措 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 02:57

    You can use %g to suppress trailing zeros. Then I think you do not need to go through the business of determining the number of places. Eg -

    var num1:Double = 5.5
    var x = String(format: "%g", num1) // "5.5"
    
    var num2:Double = 5.75
    var x = String(format: "%g", num2) // "5.75"
    

    Or this variation where the number of places is specified. Eg -

    var num3:Double = 5.123456789
    var x = String(format: "%.5g", num3) // "5.1235"
    

提交回复
热议问题