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?
In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.
The Forex-Python library provides the most direct way to get a currency conversion rate through API calls. It has different functions, which take the currency codes you want to convert from one currency to another and then return the current value. In this Python program, we are converting USD to INR.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With