jumi lee
jumi lee

Reputation: 15

how to work roundingMode in freemarker?

I think it returns 1.13 but freemarker returns 1.12.

What is right?

${(1.125)?string(",##0.00;roundingMode=HALF_UP")}

Upvotes: 1

Views: 4435

Answers (3)

ddekany
ddekany

Reputation: 31112

There are 3 problems there:

  • You need at least FreeMarker 2.3.24 to use "extended Java decimal format". It's a non-standard extension of java.text.DecimalFormat patterns, and as DecimalFormat is quite lenient, using it on an old versions will not result in error unfortunately, it's just being misinterpreted.

  • You need two ;-s, as the first one separtes the positive and negative number patterns.

  • It's halfUp, not HALF_UP. (Using HALF_UP would give an error message, but as you are using a too old FreeMarker, the whole things is just silently ignored.)

Update: https://freemarker.apache.org/docs/ref_builtins_number.html#topic.extendedJavaDecimalFormat now warns users about the first two pitfalls.

Upvotes: 1

Ori Marko
Ori Marko

Reputation: 58774

Freemarker is correct, You probably misunderstood HALF_EVEN, it is rounding to the even neighbor.

In your case 2 is even so 1.125 is rounded to 1.12.

both neighbors are equidistant, in which case, round towards the even neighbor.

In freemarker rounding constants are different:

roundingMode The value is one of up, down, ceiling, floor, halfUp, halfDown, halfEven, and unnecessary.

In your case you can use the following:

${(1.125)?string(",##0.00;; roundingMode=halfEven")}

Half even will be the default if you put none or irrelevant rounding

Java default is halfEven

The fix was in version 2.3.24. you should upgrade your version to get it working

Everywhere where Java DecimalFormat patterns are used (like in ?string('0.##') or <#setting number_format="0.##">), now it's possible to specify options like rounding mode or the symbols used, with a FreeMarker-specific extension to the DecimalFormat pattern syntax.

Upvotes: 0

Hemang Rindani
Hemang Rindani

Reputation: 348

The function HALF_EVEN is a rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.

The even neighbor fro your number 1.125 is 1.2 and thus the mode is working fine. You can use HALF_UP to get the answer as 1.3

Upvotes: 0

Related Questions