sigmapi13
sigmapi13

Reputation: 2553

XSL format-number without rounding

Is there anything similar to format-number in XSL that could take a number and format it like '#0.00' and not round it?

So,

Just format-number doesn't work because it would round 1.375 to 1.38

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

This concatenation substring mess won't work for 5 (because there is no ".") and won't add a zero to the end of 14.6

<xsl:value-of select="concat(substring-before(MY_NUMBER,'.'), '.',  substring(substring-after(MY_NUMBER,'.'),1,2))" />

I'm I going to have to do a messy:

<xsl:choose>
    <xsl:when test=""></xsl:when>
    <xsl:otherwise></xsl:otherwise>
</xsl:choose>

Thanks so much in advance!

Upvotes: 4

Views: 5323

Answers (1)

David Carlisle
David Carlisle

Reputation: 5652

I'm assuming you are restricted to XSLT 1 so something like this

<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">


<xsl:template match="/">
:
<xsl:call-template name="f">
<xsl:with-param name="n" select="5"/>
</xsl:call-template>
:
<xsl:call-template name="f">
<xsl:with-param name="n" select="14.6"/>
</xsl:call-template>
:
<xsl:call-template name="f">
<xsl:with-param name="n" select="1.375"/>
</xsl:call-template>
:
<xsl:call-template name="f">
<xsl:with-param name="n" select="-12.1234"/>
</xsl:call-template>
:
</xsl:template>

<xsl:template name="f">
<xsl:param name="n"/>
<xsl:value-of select="format-number(floor($n*1000) div 1000, '#0.00')"/>
</xsl:template>

</xsl:stylesheet>

which produces

:
5.00
:
14.60
:
1.38
:
-12.12
:

Upvotes: 10

Related Questions