Print floating point values without leading zero

后端 未结 13 1222
逝去的感伤
逝去的感伤 2020-11-30 05:21

Trying to use a format specifier to print a float that will be less than 1 without the leading zero. I came up with a bit of a hack but I assume there is a way to just drop

13条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 06:14

    The problem is to print a float without the leading zero, regardless of the sign of the float. The leading zero always precedes a decimal point. Split the printed float on '0.', and then rejoin the resulting list around just '.', as in below:

    >> flt = -.31415926
    

    -0.31415926

    >> '%.4f' % flt    # prints leading zero
    

    '-0.3142'

    >> '.'.join( ('%.4f' % flt).split('0.'))    # removes leading zero
    

    '-.3142'

提交回复
热议问题