gpt4 book ai didi

java - 如何格式化 Velocity 模板中的数字?

转载 作者:太空狗 更新时间:2023-10-29 22:59:28 28 4
gpt4 key购买 nike

我在我的 Velocity 模板中得到了一个 Java 对象。该对象有一个 double 值,我想将其格式化为 2 位小数并将其显示在我的模板中。

我获取对象的类是这样的

Class Price
{
double value;
String currency;
}

在我的速度模板中,我得到这样的值

$price.value

但我需要在显示之前将其格式化为小数点后两位。

我要转换

23.59004 到 23.59

35.7 到 35.70

3.0 到 3.00

9 点到 9 点

请告诉我如何在速度模板中做到这一点?我为此搜索了很多,发现我可以使用velocity tools,但是没有相关的例子吗?我可以在模板中使用速度工具吗?

最佳答案

Velocity 模板中有望使用 Velocity 工具;本质上,它们是添加到模板中可用变量的对象,因此您可以使用 $numberTool.format("#0.00", $val) 或类似的。如果所有可用工具都不能满足您的需求,只需创建一个 POJO 并将其添加到模板中即可。

要使其正常工作,您还应该添加以下 Maven 依赖项:

<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>

并编写如下代码:

context.put("numberTool", new NumberTool());

关于java - 如何格式化 Velocity 模板中的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8820240/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com