Help with *checks notes* simple division

Capture2

The script is preforming Integer Division, which in this case is 0 (well 0 r1).

The simplest method would be to make one or both of the numbers floating point numbers

value = 1.0/2
value = 1/2.0
value = 1.0/2.0

You could also cast one to a float, but it must be prior to the division operation.

value = float(1)/2 #yields 0.5
value = 1/float(2) #yields 0.5
value = float(1)/float(2) #yields 0.5
value = float(1/2) #yields 0 

but that is ugggggly.

The advanced way is to import the future division operator:

from __future__ import division
value = 1/2 #yields 0.5

Note: with the future import you can still get the floored answer by using the // operator

from __future__  import division
value = 1//2 #yields 0
3 Likes

I get an error when I use

from __future__ import division


I have been able to use

import datetime

ahh, didn’t think about that.

The from future import has to be at the top of the file, so it wont work from inside of a script transform, unless there’s some sneaky way to insert it that I’m unaware of.

Assuming you’re not just doing this simple operation, you could potentially put this in a project script.
image

image

I am not sure of the implications of that.

I better declare the variables as floats when dividing in a script.

@lrose how do I set the value to show two decimals as percentage?

0.00%
50.00%

I used the percent format, but the format pattern is not available

Well, you could add an additional format transform set to pattern with a pattern of #.00%, you would have to do the multiplication in the script prior to the return. Or you can do it all in the script (my preferred method, don’t really like stacking transforms if I can avoid it.

return '{0:.2f}%'.format((1/2.0)*100)
 temp= value
 	if temp==0:
		value=0
 	else :
 		value=float(temp)*0.00003472222 			

return return '{0:.2f}%'.format(value)

works, thanks

Thanks very much @lrose

EDIT: just saw this is a repeat of lrose’s answer. oops.

division between a float and an int returns a float, so you can convert one of the numbers to a float and it will give you the “real” answer:

>>> float(1)/2
0.5

if you are dividing literals you can type one of them as a float literal rather than an int literal by adding a decimal:

>>> 1.0/2
0.5

If you are dividing using variables that are ints then the second option won’t work, but the first option will:

>>> a = 1
>>> b = 2
>>> float(a)/b
0.5