Keep trailing zeroes in python

前端 未结 4 726
借酒劲吻你
借酒劲吻你 2020-12-18 22:43

I am writing a class to represent money, and one issue I\'ve been running into is that \"1.50\" != str(1.50). str(1.50) equals 1.5, and alll of a sudden, POOF.

4条回答
  •  被撕碎了的回忆
    2020-12-18 23:42

    The proposed solutions do not work when the magnitude of the number is not known in advance, which is common in scientific applications rather than in money-related ones. I give an alternative solution for those, like me, coming to this question looking for the scientific case.

    For example, if I want to print x = 1.500e-4 to three significant digits (common situation when dealing with measurements with a given uncertainty), the following command obviously does not give the correct result:

    x = 1.500e-4
    print(f"{x:.3f}")
    
    ----> 0.000
    

    Here I used the modern Python 3.6+ f-strings for the formatting.

    One may think of using the g format specifier, but this also does not give the desired result to three significant digits as the trailing zero is omitted:

    x = 1.500e-4
    print(f"{x:.3g}")
    
    ----> 0.00015
    

    The correct answer can be obtained using the g format specifier together with a rather obscure option, the hash character #, of the format-specification mini language, in the following way:

    x = 1.500e-4
    print(f"{x:#.3g}")
    
    ----> 0.000150
    

    This formatting also works unchanged in the simpler case of the original question:

    x = 1.500
    print(f"{x:#.3g}")
    
    ----> 1.50
    

提交回复
热议问题