dropping trailing '.0' from floats

后端 未结 16 2079
傲寒
傲寒 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:39
    str(x)[-2:] == '.0' and int(x) or x
    
    0 讨论(0)
  • 2020-12-05 04:42

    Using Python's string formatting (use str.format() with Python 3.0):

    from decimal import Decimal
    
    def format_number(i):
        return '%g' % (Decimal(str(i)))
    
    0 讨论(0)
  • 2020-12-05 04:45

    To print a float that has an integer value as an int:

    format = "%d" if f.is_integer() else "%s"
    print(format % f)
    

    Example

                 0.0 -> 0
                 0.1 -> 0.1
                10.0 -> 10
          12345678.9 -> 12345678.9
         123456789.0 -> 123456789
    12345678912345.0 -> 12345678912345
    12345678912345.6 -> 1.23456789123e+13
      1.000000000001 -> 1.0
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题