python:如何将货币转换为十进制?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3887469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:12:10  来源:igfitidea点击:

python: how to convert currency to decimal?

python

提问by l--''''''---------''''''''''''

i have dollars in a string variable

我在字符串变量中有美元

dollars = '.99'

how do i convert this to a decimal instead of a string so that i can do operations with it like adding dollars to it?

我如何将其转换为十进制而不是字符串,以便我可以对其进行操作,例如向其中添加美元?

采纳答案by lllluuukke

There's an easy approach:

有一个简单的方法:

dollar_dec = float(dollars[1:])

回答by Amber

If you'd prefer just an integer number of cents:

如果您只喜欢整数美分:

cents_int = int(round(float(dollars.strip('$'))*100))

If you want a Decimal, just use...

如果你想要一个十进制,只需使用...

from decimal import Decimal
dollars_dec = Decimal(dollars.strip('$'))

If you know that the dollar sign will always be there, you could use dollars[1:]instead of dollars.strip('$'), but using strip()lets you also handle strings that omit the dollar sign (5.99instead of $5.99).

如果您知道美元符号将始终存在,则可以使用dollars[1:]而不是dollars.strip('$'),但是使用strip()还可以处理省略美元符号(5.99而不是$5.99)的字符串。

回答by Tim

If you want to use Decimal:

如果要使用十进制:

from decimal import Decimal
dollars = Decimal(dollars.strip('$'))

From there adding is pretty simple

从那里添加非常简单

dollars += 1 # Would add 1 to your decimal

回答by Mark Ransom

First, strip off the '$' character. If it's always consistently the first character, that's easy:

首先,去掉“$”字符。如果它始终是第一个字符,那很容易:

dollars[1:]

To keep the cents perfect without worrying about the non-perfect representation of cents in floating point, you'll want to use Decimal values:

为了保持美分完美而不用担心浮点中美分的非完美表示,您需要使用 Decimal 值:

from decimal import *
Decimal(dollars[1:])

回答by pyfunc

Through decimal package

通过十进制包

>>> dollars = '.99'
>>> import decimal
>>> decimal.Decimal(dollars[1:])
Decimal('5.99')
>>> 

回答by gaefan

If you are only going to be adding (and not multiplying or dividing) consider just storing cents instead of dollars and not using the decimal package. I suggest using the simplest tool for the job, and decimal doesn't provide any value if you are just adding dollars and cents.

如果您只想添加(而不是乘法或除法),请考虑只存储美分而不是美元,而不是使用小数包。我建议使用最简单的工具来完成这项工作,如果您只是增加美元和美分,十进制不会提供任何价值。

回答by Tony Veijalainen

If you want to keep moneys in cents for easy rounding and sometimes '$' is missing:

如果您想将钱以美分为单位以便于四舍五入,并且有时会缺少“$”:

for dollars in ('.99','6.77'):
    cents = int(float((dollars[1:] if dollars.startswith('$') else dollars))*100)
    print '%s = %i cents = %i dollars and %i cents' % ((dollars, cents)+divmod(cents, 100))

回答by Amar

Assuming the string stored in the variable dollarswas generated using python's locale module. A potentially cleaner way to convert it back to float (decimal) is to use the atoffunction from the same module. It should work as long as you use the same setlocaleparameters in both directions (from currency to string and vice-versa).

假设存储在变量中的字符串dollars是使用 python 的 locale 模块生成的。将其转换回浮点数(十进制)的一种可能更简洁的方法是使用atof来自同一模块的函数。只要您setlocale在两个方向(从货币到字符串,反之亦然)使用相同的参数,它就应该起作用。

for instance:

例如:

import locale
locale.setlocale(locale.LC_ALL, '')
value = 122445.56
value_s = locale.currency(value, grouping=True)
#generates 2,445.56

to convert it back:

将其转换回来:

value2 = locale.atof(value_s[1:])
#value2 = 122445.56 
value == value2 #True

回答by Brian Powell

I know this an old question, but this is a very simple approach to your problem that's easily readable:

我知道这是一个老问题,但这是解决您的问题的一种非常简单的方法,易于阅读:

for:

为了:

dollars = '.99'
dollars = dollars.replace("$","").replace(",","")
/* 5.99 */

It also works with a larger number that might have a comma in it:

它也适用于可能有逗号的较大数字:

dollars = '1,425,232.99'
dollars = dollars.replace("$","").replace(",","")
/* 1425232.99 */

回答by jmunsch

Here's another example of converting a messy currency string into a decimal rounded down to the cent:

这是将凌乱的货币字符串转换为四舍五入到美分的小数的另一个示例:

from decimal import Decimal, ROUND_DOWN

messy = ',   , 111.2199  ,,,'

less_messy = Decimal(''.join(messy.replace(',','').split()).replace('$',''))
converted = less_messy.quantize(Decimal(".01"), rounding=ROUND_DOWN)

print(converted)
1111.21

Other rounding options include: ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_UP

其他四舍五入选项包括:ROUND_HALF_UP, ROUND_HALF_DOWN,ROUND_UP