-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.

5
  • 2
    Isn't` int(value) what you want? Commented Jan 28, 2018 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. Commented Jan 28, 2018 at 13:52
  • See my updated answer. Commented Jan 28, 2018 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. Commented Jan 28, 2018 at 13:56
  • 1
    Possible duplicate of Safest way to convert float to integer in python? Commented Jan 28, 2018 at 13:59

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

it's probably worth mentioning that int() trunctuates the value (and round should be used if the floating point value should be rounded)
@UnholySheep I'm aware of that.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.