0

In JavaScript we have +number which converts a string into a number based on its value, as shown below:

x = '123' => +x returns 123

y = '12.3' => +y returns 12.3

Now if I use int in python it returns:

x = '123' => int(x) returns 123

y = '12.3' => int(y) returns 12 which is wrong as it should return 12.3

Whereas if I use float:

x = '123' => float(x) returns 123.0 which is wrong as it should return 123 only though I know 123.0 is same as 123 but I want to parse it to some other query language which identifies the numbers as mentioned above.

y = '12.3' => float(y) returns 12.3

Shivam Sahil
  • 4,055
  • 3
  • 31
  • 62
  • `int('12.3')` doesn't return `12`... It raises a `ValueError`... – Tomerikoo Nov 22 '20 at 12:22
  • Does this answer your question? [python converting strings in list to ints and floats](https://stackoverflow.com/questions/48441382/python-converting-strings-in-list-to-ints-and-floats) – iBug Nov 22 '20 at 12:22
  • Does this answer your question? [How do I parse a string to a float or int?](https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int) Specifically [this answer](https://stackoverflow.com/a/379966/6045800) – Tomerikoo Nov 22 '20 at 12:22

2 Answers2

1

JavaScript doesn't have types for integers like other languages (like C) do, so 123 in JS is really 123.0 stored as double but displayed without the decimals. (There's BigInt if you want to learn further, but it would have been 123n).

In Python, you can use literal_eval to get the numeric (literal) value from a string representation:

import ast

ast.literal_eval("123")    # -> 123   (int)
ast.literal_eval("123.")   # -> 123.0 (float)
ast.literal_eval("123.0")  # -> 123.0 (float)
iBug
  • 35,554
  • 7
  • 89
  • 134
1

If, for some reason you do not want to use literal_eval, I want to offer another solution using regex. There isn't a necessarily "pretty" built-in method in Python to convert str representations of int and float to int and float respectively.

import re

def conv(n):
    if isinstance(n, str) and len(n) > 0:
        if re.match(r"^-{0,1}[0-9]+$", n):
            return int(n)
        elif re.match(r"^-{0,1}[0-9]+(\.|e)[0-9]+$", n):
            return float(n)
    return n
>>> conv("-123")
-123
>>> conv("123.4")
123.4
>>> conv("2e2")
200.0
gmdev
  • 2,725
  • 2
  • 13
  • 28