Ivan Kozin
Ivan Kozin

Reputation: 17

Freemarker: keep trailing zeroes in BigDecimal

I'd like to copy a BigDecimal value with an arbitrary number of traling zeroes into a Freemarker template as-is (e.g., if calling value.toString() in Java results in 123.0000, I want to see exactly 123.0000 inserted into template).

However, using the built-ins (like ?string) or just ${valueWithZeroes} always seems to strip trailing zeroes away. Using ?string[...] is out of the question as the exact number of trailing zeroes is unknown. AFAIK, there's a way to call BigDecimal's own toString method from Freemarker template using ?api - however, the docs seem to disourage doing this. So I wonder if there's any other way to achieve that using Freemarker itself, without falling back to Java methods.

Upvotes: 0

Views: 879

Answers (1)

ddekany
ddekany

Reputation: 31112

I believe java.text.DecimalFormat can't do that, and therefore FreeMarker can't do that out of the box. But, you can define your own CustomNumberFormatFactory, and do whatever is possible in Java. See example for that here: https://freemarker.apache.org/docs/pgui_config_custom_formats.html. So you do something like HexTemplateNumberFormatFactory there, and you can also set your custom number format as the default number format (by setting the number_format to "@hex" in the example).

Note that if you are just using BigDecimal.toString as is, the formatting won't consider the Locale. So your decimal separator will be wrong in some languages.

Upvotes: 1

Related Questions