Putting a fraction into parentheses breaks math?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By somebody1134

I came across a really strange quirk today while coding a “shield” health system:

var Armor = 50.0

func _ready():
    damage(50.0)

func damage(amount):
    Armor -= amount * 2 / 3

This sets armor to the expected value (~16.66), however:

func damage(amount):
    Armor -= amount * (2 / 3)

This does not subtract anything from the armor. Armor remains at 50.

I prefer to have my fractions formatted in parentheses for more readable code. Why does this make a difference?

:bust_in_silhouette: Reply From: kidscancode

This is about integer division. 2 / 3 == 0 while 2.0 / 3.0 = 0.6667

The reason the first version works is because of order of operations. amount * 2 results in a float, so dividing by 3 results in the expected value.

As long as one of the operands is a float, then the result will be a float, so you can do:

Armor -= amount * (2 / 3.0)

Duh! I can’t believe I forgot about that. I just needed a fresh pair of eyes on it, thanks :slight_smile:

somebody1134 | 2020-06-09 07:14