I have some strings representing numbers with specific currency format, for example:
money="$6,150,593.22"
I want to convert this string into the number
6150593.22
What is the best way to achieve this?
We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.
The atof() function converts a character string to a double-precision floating-point value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type.
To convert the integer to float, use the float() function in Python. Similarly, if you want to convert a float to an integer, you can use the int() function.
Try this:
from re import sub from decimal import Decimal money = '$6,150,593.22' value = Decimal(sub(r'[^\d.]', '', money))
This has some advantages since it uses Decimal
instead of float
(which is better for representing currency) and it also avoids any locale issues by not hard-coding a specific currency symbol.
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