使用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
相关产品推荐
相关产品推荐

