Formatting numbers, excluding trailing zeroes

2020-03-31 07:50发布

问题:

first time SO user :)

I know that I can format a number like this:

format-number($value, '###,###.00')

But I would like to remove the dot and the zeroes if $value is zero.

So,

37368 -> 37,368
2.666667 -> 2.66

Is this possible using just number formatting (doesn't seem like it) or do I have to do something along the lines of

if (int(value) == value ) {...}

回答1:

format-number($value, '###,###.##')


回答2:

xpath 2.0 contains conditional logic if..then..else but in the more likely case that you're in xpath 1.0 I'm afraid you'll have to either rely on XSLT to do this for you, i.e:

<xsl:variable name="myvar">
  <xsl:choose>
    <xsl:when test="$value > 0">
      <xsl:select="format-number($value, '###,###.00')"/>
    </xsl:when>
    <xsl:otherwise>0</xsl:otherwise>
  </xsl:choose>>
</xsl:variable>

..or mixin an extension (.NET can do this natively, EXSLT exists otherwise, probably more options available)

To the best of my knowledge no xpath functions exist to get you out of this, but I could be missing something exotic.