【问题标题】:Floats rounded down in AWS AppSync VTL在 AWS AppSync VTL 中四舍五入的浮点数
【发布时间】:2022-10-07 22:55:27
【问题描述】:
我正在 AWS AppSync 中创建解析器响应映射,用于执行数学计算并将百分比值作为浮点数返回:
#set( $result = $ctx.source.total * 100 / 365000 )
$result
然而,VTL 每次都会将其向下舍入到最接近的整数,例如 1.0、2.0 等。
给定5000 * 100 / 365000:
预期 - 1.36
结果 - 1.0
无论如何我可以做到这一点吗?或者我是否需要考虑使用 Lambda(对于如此简单的事情感觉有点过头了)。
【问题讨论】:
标签:
aws-appsync
vtl
aws-appsync-resolver
【解决方案1】:
在上面的示例中,结果将为 1.0,因为 1.36 向下舍入为 1.0。要将结果作为浮点数返回,您可以使用 Math.round() 函数并将结果除以 100:
#set( $result = Math.round($ctx.source.total * 100 / 365000) / 100 )
$result
这将返回结果为带有 2 位小数的浮点数。
为了解决这个问题,不使用 Lambda 并且不使用 Math.round() 函数,您可以使用以下 VTL:
#set( $result = $ctx.source.total * 100 / 365000 )
#set( $result = $util.parseJson($util.toJson($result)) )
$result
这将返回结果为带有 2 位小数的浮点数。