JamesFrost
JamesFrost

Reputation: 769

Terraform - Issues Converting From Decimal To Percentage

I'm trying to convert decimal numbers to percentages using Terraform. It works for some decimals, but not others.

For example:

$ terraform console
> 0.2 * 100
20
> 0.01 * 100
0.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999
> 0.005 * 100
0.49999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999996

Calling ceil or floor won't be appropriate in this case.

I've replicated this behaviour in Terraform 1.1.4 and 1.2.3.

Any ideas on how to resolve this?

Upvotes: 1

Views: 755

Answers (1)

Will
Will

Reputation: 2410

Update using format() as suggested by @Matt Schuchard :

tonumber(format("%.2f",  0.2 * 100)) # 20
tonumber(format("%.2f",  0.01 * 100)) # 1
tonumber(format("%.2f",  0.005 * 100)) # 0.5

Upvotes: 1

Related Questions