Reputation: 15927
How can I tabulate data in FreeMarker while still keeping precision and not losing cents due to double of float reprensations?
<#assign totalSalaries = 0>
<#list employees as employee>
<#assign totalSalaries = totalSalaries + emplpoyee.salary>
</#list>
${totalSalaries?string.currency}
Personally, I prefer to use longs and keep everything in cents but I couldn't find an easy solution to convert that to a currency value. Either way, if I'm using long
or BigDecimal
(it's easy to convert long with cents to BigDecimal) how can I guarantee that the total salaries printed out won't lose any cents due to precision errors of doubles or floats? In other words, how does FreeMarker decide what type of variable total is defined as?
Upvotes: 0
Views: 610
Reputation: 31122
FreeMarker does calculations (and the numerical type conversions needed as part of that) with the ArithmeticEngine
, which is a configuration setting. The default of that setting is BigDecimalEngine
, which converts everything to BigDecimal
before doing anything with them, and keeps the results as BigDecimal
as well. So at least with the default you won't lose any digits.
Upvotes: 2