Hi I would like to know if there is any way to obtain a float result from a division between two integers other than using "from __future__ import division"?

I am not looking for the .0 'trick'. Example 4/5.0 = 0.8.

I want to be able to do 4/5 = 0.8.

Thanks.

Recommended Answers

All 7 Replies

No matter how you do it, the fraction part is the result of the remainder / divisor so still need a division!

Could fake it somewhat.
In integer
part %
----- = -------
whole 100

So could calculate a whole integer form of the remainder and stick your own decimal point as a string character!

(4 * 100) / 5 = 80

4 / 5 = 0
"0" "." "80" 0.80

No matter how you do it, the fraction part is the result of the remainder / divisor so still need a division!

Could fake it somewhat.
In integer
part %
----- = -------
whole 100

So could calculate a whole integer form of the remainder and stick your own decimal point as a string character!

(4 * 100) / 5 = 80

4 / 5 = 0
"0" "." "80" 0.80

I was just wondering if there was any other way other than "from __future__ import division" because further in the program I might want to have 4/5 = 0, and because of that I won't.

Is it possible to unload from __future__ import division?

No idea. Sorry!

No idea. Sorry!

I guess I will have to do the .0 'trick'. Maybe some other folk will know a way.

Thanks wildgoose for your help.

I guess I will have to do the .0 'trick'. Maybe some other folk will know a way.

Thanks wildgoose for your help.

You could do this:

float(4)/5

Or if you wanted to perform the from __future__ import division and still get integer returns you could simply turn the answer into an int like this:

>>> ans = 5 / 2
>>> ans
2.5
>>> int(ans)
2
>>>

You could update to Python 3.1 where '/' is the floatingpoint division and '//' is the integer division.

Actually, with Python2 versions, 4./5 would be simpler to type then 4.0/5 or float(4)/5 :)

You could update to Python 3.1 where '/' is the floatingpoint division and '//' is the integer division.

Actually, with Python2 versions, 4./5 would be simpler to type then 4.0/5 or float(4)/5 :)

Thanks for the two tips. I will keep that in mind.

Cheers :icon_wink:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.