Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

i have dollars in a string variable

dollars = '$5.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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
800 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.99 instead of $5.99).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...