-2

I have got the value from database 350,000,000.00 now I need to convert it to 350000000. Please provide a solution on this using Python 3.6+ version

Thanks

Kuladip
  • 154
  • 1
  • 10
  • the comma's are included? – Willem Van Onsem Jun 20 '17 at 09:50
  • 1
    Possible duplicate of [Python parse comma-separated number into int](https://stackoverflow.com/questions/2953746/python-parse-comma-separated-number-into-int) – doctorlove Jun 20 '17 at 09:54
  • 1
    Possible duplicate of [How do I use Python to convert a string to a number if it has commas in it as thousands separators?](https://stackoverflow.com/questions/1779288/how-do-i-use-python-to-convert-a-string-to-a-number-if-it-has-commas-in-it-as-th) – Tezra Jun 20 '17 at 12:30
  • This is not duplicate. I am getting number with comma separated, then I need to add "", then remove comma and dot(.). – Kuladip Jun 21 '17 at 07:49

3 Answers3

4

Let the input be in a variable, say

a="350,000,000.00"

Since, the digits are comma , separated, that needs to be removed.

a.replace(",","")
>>> 350000000.00

The resultant string is a float. When we directly convert the string to integer, it will result in an error.

int(a.replace(",",""))
>>>Traceback (most recent call last):
  File "python", line 2, in <module>
ValueError: invalid literal for int() with base 10: '350000000.00'

So, convert the number to float and then to int.

int(float(a.replace(",","")))
>>>350000000
voidpro
  • 1,652
  • 13
  • 27
  • Please note that I am getting 350,000,000.00 not "350,000,000.00" . How I will convert 350,000,000.00 to "350,000,000.00" . please let me know – Kuladip Jun 20 '17 at 11:03
  • @Kuladip Just read, it is sourced from DB. The values will be string by default. Try using the string function on the field. – voidpro Jun 20 '17 at 11:09
1

Store the value in a variable and then parse it with int(variable_name)

eg. If you store the value in variable a, just write int(float(a))

1
def convert(a):
    r = 0
    s = a.split(".")[0]
    for c in s.split(","):
        r = r * 1000 + int(c)
    return r

s = convert("350,000,000.00")
alkaya
  • 145
  • 6
  • Please note that I am getting 350,000,000.00 not "350,000,000.00" . How I will convert 350,000,000.00 to "350,000,000.00" . please let me know – Kuladip Jun 20 '17 at 11:03