Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast to Integer Only If "Lossless"?

Tags:

python

I wish to cast a string or a number to an integer only if the casting is "lossless" or, another way to put it, only if the string or number is indeed an integer.

For instance,

  • 3.0 (a float that is indeed an integer) -> 3.
  • '3.000' (a string that is an integer) -> 3.
  • 3.1 -> exception raised.
  • '4.2' -> exception raised.

Directly doing int(x) will convert 3.1 to 3.

This is the best I have:

def safe_cast_to_int(x):
    int_x = int(x)
    if np.issubdtype(type(x), np.floating):
        assert int_x == x, \
            f"Can't safely cast a non-integer value ({x}) to integer"
    return int_x

but I wonder if there is a better or more Pythonic way?

like image 706
Sibbs Gambling Avatar asked Nov 17 '25 02:11

Sibbs Gambling


1 Answers

If I understand you correctly, you only want to cast something if it's a whole number. If that's the case, you could first cast it to a float and then check with float.is_integer() function if it's an integer.

Here are the examples with values of the question.

>>> float('3.0').is_integer()
True
>>> float('3.000').is_integer()
True
>>> float('3.1').is_integer()
False
>>> float('4.2').is_integer()
False
like image 67
Ruben Veldman Avatar answered Nov 19 '25 15:11

Ruben Veldman