You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java SpringBoot+Thymeleaf中如何将GPU价格从科学计数法转为十进制显示

解决Thymeleaf中科学计数法价格转十进制显示的问题

有两种常用方案可以解决这个问题,根据项目场景选择即可:

方案一:后端Java代码处理(推荐)

在GPU实体类中添加返回格式化后价格的方法,或者在组装数据时提前格式化价格,把逻辑放在后端更易维护:

import java.text.DecimalFormat;

public class GPU {
    // 原有字段
    private Double price;
    private String name;
    private String linkToko;
    private String imageUrl;

    // 新增方法:返回格式化后的价格字符串
    public String getFormattedPrice() {
        // 可按需调整格式,比如保留两位小数用"#,###.00"
        DecimalFormat df = new DecimalFormat("#,###");
        return df.format(price);
    }

    // 原有getter、setter方法
}

然后在Thymeleaf中直接调用该方法:

<th:block th:each="gpu : ${gpus}">
    <option 
        th:value="${gpu.price}"
        th:text="${gpu.name + ' - IDR ' + gpu.formattedPrice}"
        th:attr="data-link=${gpu.linkToko}, data-image=${gpu.imageUrl}">
        GPU Name
    </option>
</th:block>

方案二:前端Thymeleaf内置工具类处理

直接用Thymeleaf自带的#numbers工具类格式化价格,无需修改后端代码:

<th:block th:each="gpu : ${gpus}">
    <option 
        th:value="${gpu.price}"
        th:text="${gpu.name + ' - IDR ' + #numbers.formatDecimal(gpu.price, 0, 'COMMA', 0, 'POINT')}"
        th:attr="data-link=${gpu.linkToko}, data-image=${gpu.imageUrl}">
        GPU Name
    </option>
</th:block>

参数说明:

  • 第一个0:整数部分最少显示位数
  • COMMA:整数部分的千位分隔符
  • 第二个0:小数部分最少显示位数(不需要小数可设为0)
  • POINT:小数部分的分隔符

如果不需要千位分隔符,可简化为#numbers.formatInteger(gpu.price, 0)。

内容的提问来源于stack exchange,提问作者SaintNave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 20:32:18