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

使用Thymeleaf的numbers.formatCurrency为何显示奇怪符号?

问题原因与解决方案

你的代码:

<div class="col-md-5"> Valor: <span th:text="${#numbers.formatCurrency(order.negotiatedValue)}">200,99</span></div>

原因

显示符号¤是因为Thymeleaf无法识别正确的区域设置(Locale),导致货币符号缺失。当#numbers.formatCurrency未指定Locale时,会使用当前上下文的默认Locale,如果这个Locale没有设置为巴西葡萄牙语(pt_BR),就会使用通用Locale,无法解析出巴西雷亚尔的符号R$。

解决方案(无需硬编码R$)

1. 全局配置Spring MVC的LocaleResolver

通过配置LocaleResolver,让整个应用默认使用巴西Locale:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver resolver = new SessionLocaleResolver();
        resolver.setDefaultLocale(new Locale("pt", "BR"));
        return resolver;
    }
}

配置后,所有Thymeleaf的货币格式化都会自动使用R$符号。

2. 在模板中直接指定Locale

如果只需要在特定模板生效,可以给formatCurrency方法传入巴西Locale参数:

<div class="col-md-5"> Valor: <span th:text="${#numbers.formatCurrency(order.negotiatedValue, new java.util.Locale('pt', 'BR'))}">200,99</span></div>

3. 设置JVM默认Locale

在应用启动时添加JVM参数:

-Duser.locale=pt_BR -Duser.country=BR

或者在应用初始化代码中设置:

Locale.setDefault(new Locale("pt", "BR"));

这种方式会影响整个JVM的Locale设置,适合全应用都需要巴西区域配置的场景。

内容的提问来源于stack exchange,提问作者Bruno Fernandez Ellerbach

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:18:29