-1

I wrote a simple script with a single function but i want to convert the result from float to an integer data type. Is it possible in this case?

This is the script

def minutes_to_hours(minutes):
    hours=minutes/60
    return hours
def seconds_to_hours(seconds):
    hours=seconds/int(3600)
    return hours
print(minutes_to_hours(100))
print(seconds_to_hours(int(3600)))

And the result is

1.6666666666666667
1.0

The result is correct but as you can see i want to change the data type from float to an integer (1 rather than 1.0), is it possible?

Related to python functions.

  • 2
    Isn't` `int(value)` what you want? – iBug Jan 28 '18 at 13:50
  • yeah, the value should be an integer 1, rather than 1.0, is it possible? Please correct my script if any changes required. – Arpan Sharma Jan 28 '18 at 13:52
  • See my updated answer. – iBug Jan 28 '18 at 13:55
  • In your specific case, you could use integer division `//`instead of floating point division `/`, but the answer given by @iBug is more generic. – OBu Jan 28 '18 at 13:56
  • 1
    Possible duplicate of [Safest way to convert float to integer in python?](https://stackoverflow.com/questions/3387655/safest-way-to-convert-float-to-integer-in-python) – Aran-Fey Jan 28 '18 at 13:59

2 Answers2

2

Python's builtin function does the job:

>>> print(int(seconds_to_hours(int(3600)))
1
>>> print(type(int(seconds_to_hours(int(3600))))
<class 'int'>
>>> 

Note that your code hours=seconds/int(3600) does not generate an integer, as opposed to C. If you want to do integer division, use double slash:

hours=seconds//int(3600)
#            ^^

If you want to convert whatever into int without knowing whether it can, use this function:

def try_int(v)
    try:
        return int(v)
    except ValueError:
        return v

Then you'll be able to convert only those that are able to be converted into int into int.

iBug
  • 35,554
  • 7
  • 89
  • 134
1

Simply type cast your result.

e.g.

a = 1.000
b = int(a)  #typeCasting to int
print(b)    # or return (int(return Value)) in your code
LMSharma
  • 279
  • 3
  • 10