Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSL format-number without rounding

Tags:

rounding

xslt

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,

  • 5 would become 5.00
  • 14.6 would become 14.60
  • 1.375 would become 1.37

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!

like image 471
sigmapi13 Avatar asked Sep 01 '25 10:09

sigmapi13


1 Answers

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
:
like image 191
David Carlisle Avatar answered Sep 05 '25 05:09

David Carlisle