0

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?

Chetan chadha
  • 558
  • 1
  • 4
  • 19
Stephane Grenier
  • 15,527
  • 38
  • 117
  • 192

1 Answers1

2

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.

ddekany
  • 29,656
  • 4
  • 57
  • 64
  • Do you know where this is documented? I looked for a while and couldn't find anything so it would be great to see where I missed it ;) – Stephane Grenier Aug 04 '17 at 20:11
  • If you go through the configuration settings in the API, you can bump into it... surely it needs some more mentions. I will look into it. – ddekany Aug 05 '17 at 08:00
  • Thank you, I found it. Yes if it's all possible I would recommend adding this somewhere on the website rather than just the API. In any case thank you again, it's very much appreciated. By the way I find FreeMarker to be a very amazing templating engine!! Awesome work!! – Stephane Grenier Aug 05 '17 at 19:55