hashicorp/hil

Prefer promotion from int to float, vs. the converse

apparentlymart opened this issue · 2 comments

(Originally reported in hashicorp/terraform#10778.)

Currently when type-checking an arithmetic operation we take the type from the first operand and then attempt to implicitly convert the remaining operands to match. This causes a surprising result when dealing with the numeric types:

  • 0.5 * 100 => 50.0 because integer 100 is converted to float 100.0
  • 100 * 0.5 => 0 because float 0.5 is converted to int 0

The automatic conversion to int in the second case is lossy and there's no significant use-case where this behavior is desirable, so we should instead be smarter about our conversions and prefer to convert to float if any of the arguments are floats, regardless of argument order.

arj22 commented

@mitchellh I have allocated_storage set to 100 for an RDS Instance and the following arithmetic operation results in an integer 80 instead of 80.0
threshold = "${0.8 * aws_db_instance.duo.allocated_storage}"
I am on Terraform 9.2
Is there a temporary workaround for this?

@AnudeepReddyJ21 whole numbers will be written without decimal places regardless of what type they have internally. I expect it is doing floating point arithmetic and then converting the float to string as "80".

Ultimately results in HIL always get converted strings anyway, so it doesn't make any difference whether the result is a float or an int.

It sounds like this is causing some sort of Terraform-specific problem for you. If so, I'd suggest to ask in one of the Terraform community forums where there are more Terraform experts around to help.