将浮点数转换为美元和美分

Converting Float to Dollars and Cents(将浮点数转换为美元和美分)
本文介绍了将浮点数转换为美元和美分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

首先,我尝试过这篇文章(以及其他):Python 中的货币格式.它对我的变量没有影响.我最好的猜测是因为我使用的是 Python 3,而那是 Python 2 的代码.(除非我忽略了某些东西,因为我是 Python 新手).

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).

我想将浮点数(例如 1234.5)转换为字符串,例如$1,234.50".我该怎么做呢?

为了以防万一,这是我编译的代码,但不影响我的变量:

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)

同样失败:

money = float(1234.5)
print(money) #output is 1234.5
'${:,.2f}'.format(money)
print(money) #output is 1234.5

推荐答案

在 Python 3.x 和 2.7 中,您可以简单地这样做:

In Python 3.x and 2.7, you can simply do this:

>>> '${:,.2f}'.format(1234.5)
'$1,234.50'

:, 添加逗号作为千位分隔符,.2f 将字符串限制为小数点后两位(或添加足够的零以达到小数点后两位,视情况而定)在最后.

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.

这篇关于将浮点数转换为美元和美分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)