Reputation: 3688
I am creating a resolvers response mapping in AWS AppSync which is meant to perform a math calculation and return a percentage value as a float:
#set( $result = $ctx.source.total * 100 / 365000 )
$result
However VTL rounds this down each time to the nearest whole number such as 1.0
, 2.0
etc.
Given 5000 * 100 / 365000
:
Expected - 1.36
Result - 1.0
Is there anyway I can achieve this? or do I need to look towards using a Lambda (which feels overkill for something so simple).
Upvotes: 0
Views: 489
Reputation: 1267
The problem is that $ctx.source.total
, 100
, and 365000
are all treated as integers (java.lang.Integer) by VTL.
VTL does support floating point numbers via java.lang.Double. The VTL syntax for a double instead of an integer is just 100.0
instead of 100
.
If any of the numbers in the assignment are doubles,$result
will be a double.
So you could do this and get 1.36986301369863
:
#set( $result = $ctx.source.total * 100.0 / 365000 )
Here's a link to some examples and example output:
https://mappingtool.dev/app/appsync/3d44255e560fa075b45bfa08afbb6fe4
Upvotes: 1
Reputation: 3767
In the case of the example above, the result would be 1.0 because 1.36 is rounded down to 1.0. To return the result as a float, you can use the Math.round() function and divide the result by 100:
#set( $result = Math.round($ctx.source.total * 100 / 365000) / 100 )
$result
This will return the result as a float with 2 decimal places.
To solve this problem, without using a Lambda and without using the Math.round() function, you can use the following VTL:
#set( $result = $ctx.source.total * 100 / 365000 )
#set( $result = $util.parseJson($util.toJson($result)) )
$result
This will return the result as a float with 2 decimal places.
Upvotes: 0