What have I missed, when worked with division in Jython?

Took me a while to figure out why my oee calculations was all zeros.
But after a little testing I figured out that I had to treat all my input values as floats by using float(a) in my calculation in my scripts, is this a Jython 2.7.3 feature ?


What you are experiencing is normal behavior for int division. If all ints are being used in the calculation, the result will be an int datatype. However, if a float is involved in the division, the result will be float. Consequently, if you need a float (decimal) answer, and all your inputs are ints, you will need to cast at least one of them to a float prior to the calculation or within the calculation itself.

To add to this, python doesn't have distinct recognition of floats, so your declaration of an float as a static number can simply be:


print "Result int = ", (a/b)

thanks for responses but I tried this

And this work fine

Is that Python 2.7 (which is what Ignition's Jython is based on)?

No it was on my own Python 3.9.1 I just tried there for a test

From the Jython Spec:

"For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result is a long integer if either operand is a long integer, regardless of the numeric value"

1 Like

The division operator changed in python 3.x, it's now a float division operator.
You get the same integer division behavior with a new operator: '//'
For example:

>>> 3 / 2
>>> 3 // 2

You need to test it in Designer's Script Console.

Integer division

I know see my first post, but thanks for all the answers, I was just a little bit puzzled by the result I got, but now I know how to do it right. Or do you just need to define the datatype ?

Putting the number in float() is as close as you can get to declaring the datatype, but as David pointed out, just adding the decimal yourself makes the number behave as a float.