dropping trailing '.0' from floats

后端 未结 16 2222
傲寒
傲寒 2020-12-05 03:54

I\'m looking for a way to convert numbers to string format, dropping any redundant \'.0\'

The input data is a mix of floats and strings. Desired output:

0

16条回答
  •  孤城傲影
    2020-12-05 04:45

    I was dealing with a value from a json dictionary (returned by an API). All the above didnt help me so i constructed by own helper function. It truncates all the trailing zeros.

    I Hope it helps someone out there

    def remove_zeros(num):
        nums = list(num)
        indexes = (list(reversed(range(len(nums)))))
        for i in indexes:
            if nums[i] == '0':
                del nums[-1]
            else:
                break
        return "".join(nums)
    
    num = "0.000000363000"
    print(remove_zeros(num))
    

    prints :

        0.000000363
    

提交回复
热议问题