XSL - rounding/format-number problem

Viewed 71647

I'm trying to get the value of a number to 2 dec places from my xml.

XML:<Quantity>0.0050</Quantity>

XSL:<xsl:value-of select="format-number($quantity, '####0.00')" />

However XSL seems to have a problem with this value and outputs 0.00 in one area of the page and 0.01 in the other. Of course in this situation it is favourable to have 0.01 output in all areas.

Another area has the value 4.221 yet the XSL is outputting 4.23.

I do realise that format-number as a method converts a number to a string.

Not sure how to fix this.


EDIT:

Ok after a bit of mucking around i found that this works:

<xsl:value-of select='format-number( round(100*$quantity) div 100 ,"##0.00" )' />

Via this website

As this guy mentions XSL uses 'bankers rounding' to round to even numbers instead of the bigger ones.

The solution hardly seems elegant, and means adding a ton of extra functions to an already bulky and complicated XSL file. Surely i'm missing something?

4 Answers

Compared to all above answers i found

<xsl:value-of select="format-number(xs:decimal($quantity), '####0.00')" />

is useful, it is not truncating any decimal point values. truncating exactly specified numbers. if number is in Exponential format we can use as follows:

<xsl:value-of select="format-number(xs:decimal(number($quantity)), '####0.00')" />

Thanks

I've also encountered the issue whereby if you did round($number * 100) div 100 you get a floating point representation of .4999999 and the rounding doesn't work properly.

To get around this, This seems to work: round($number * 1000 div 10) div 100

Related