本文介绍了将浮动转换为美元和美分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 首先,我已经尝试过这个帖子(其中包括): Python中的货币格式。它对我的变量没有影响。我最好的猜测是,这是因为我使用的是Python 3,这是Python 2的代码。(除非我忽略了一些,因为我是Python的新手)。 我想将浮点数(例如1234.5)转换为一个字符串,例如$ 1,234.50。我怎么会这样做? 为了以防万一,这里是我编译的代码,但不影响我的变量: money = float(1234.5) locale.setlocale(locale.LC_ALL,'') locale.currency(money ,grouping = True) 也不成功: 解决方案 3.x和2.7,你可以简单地做到这一点: >>>格式(1234.5)'$ 1,234.50' '$ {:,。2f} :,将一个逗号作为千位分隔符,而 .2f 将字符串限制为两位小数(或。加上足够的零来得到2个小数位,视情况而定)First of all, I have tried this post (among others): Currency formatting in Python. It has no affect on my variable. My best guess is that it is because I am using Python 3 and that was code for Python 2. (Unless I overlooked something, because I am new to Python).I want to convert a float, such as 1234.5, to a String, such as "$1,234.50". How would I go about doing this?And just in case, here is my code which compiled, but did not affect my variable:money = float(1234.5)locale.setlocale(locale.LC_ALL, '')locale.currency(money, grouping=True)Also unsuccessful:money = float(1234.5)print(money) #output is 1234.5'${:,.2f}'.format(money)print(money) #output is 1234.5 解决方案 In Python 3.x and 2.7, you can simply do this:>>> '${:,.2f}'.format(1234.5)'$1,234.50'The :, adds a comma as a thousands separator, and the .2f limits the string to two decimal places (or adds enough zeroes to get to 2 decimal places, as the case may be) at the end. 这篇关于将浮动转换为美元和美分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-19 11:02