Skip to content

Conversation

@jasmith-hs
Copy link
Contributor

Truthiness for non-integer numbers functions differently in Jinjava than it does in Jinja. The following should print yes, but since it currently only takes the Number.intvalue(), it would return false. This PR fixes the issue by checking which type of Number the object is.

{% if 0.5 %}
yes
{% else %}
no
{% endif %}

@jasmith-hs jasmith-hs requested review from boulter and mattcoley May 16, 2022 14:15
Comment on lines 42 to 54
if (object instanceof Integer) {
return (Integer) object != 0;
}
if (object instanceof Double) {
return (Double) object != 0;
}
if (object instanceof Long) {
return (Long) object != 0;
}
if (object instanceof Short) {
return (Short) object != 0;
}
return (Float) object != 0;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternatively, I could just do:

return ((Number)object).doubleValue() != 0;

Copy link
Contributor

@jmaroeder jmaroeder May 16, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately I don't think that will quite work - Python doesn't treat 0.0 as truthy

My mistake, it does! This is shorter and more to the point

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I wrote it like that thinking it would be faster, but I tested it. This shorter way is faster for longs, about the same time for floats and ints so I'm going to do the simpler approach

return b.booleanValue();
}

if (object instanceof Number) {
Copy link
Contributor

@boulter boulter May 16, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are more subclasses of Number. While you don't have to handle them all, perhaps a sane default would be to use Number.floatValue() to avoid a potential bad cast to Float.

}

@Test
public void itEvaluatesIntegers() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

might be worth a utility function here that takes a and b and does the assertions so you're not duplicating the code for every type.

@jasmith-hs jasmith-hs merged commit 8a316e3 into master May 18, 2022
@jasmith-hs jasmith-hs deleted the number-truthy branch May 18, 2022 14:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants