xsltlife
xsltlife

Reputation: 163

Rounded values in XSLT

I want to use rounded values using XSLT.

Input:

<Field>
  <Double type="one">-0.1</Double>
  <Double type="one">1.43</Double>
  <Double type="two">9548996</Double>
  <Double type="two">651050</Double>
</Field>

Output should be:

<ans>-</ans>
<ans>+1</ans>
<ans>9.5</ans>
<ans>651</ans>

Logic:

Tried code:

<xsl:template match="Field">
  <xsl:if test="Double/@type eq 'one'">
    <xsl:value-of select='format-number( round(100*Double) div 100 ,"##0.00" )' />
  </xsl:if>
  <xsl:if test="Double/@type eq 'two'">
    <xsl:value-of select='format-number( round(100*Double) div 100 ,"##0.00" )' />
  </xsl:if>
<xsl:template>

Help me to resolve this. I am using XSLT 2.0

Upvotes: 0

Views: 205

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116959

If I ignore your example's expected output and refer only to the stated logic, it could be:

XSLT 2.0

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Double[@type='one']">
    <ans>
        <xsl:if test="number(.) gt 0">+</xsl:if>
        <xsl:value-of select="round(.)"/>
    </ans>
</xsl:template>

<xsl:template match="Double[@type='two']">
    <ans>
        <xsl:variable name="n" select=". div (if (number(.) gt 1000000) then 1000000 else 1000)"/>
        <xsl:value-of select="round($n * 10) div 10"/>
    </ans>
</xsl:template>

</xsl:stylesheet>

Applied to your input example, this will return:

Result

<?xml version="1.0" encoding="UTF-8"?>
<Field>
  <ans>-0</ans>
  <ans>+1</ans>
  <ans>9.5</ans>
  <ans>651.1</ans>
</Field>

Upvotes: 1

Related Questions