Replacing NaN in XSLT 1.0

5. March 2011

As I was building a nice little XSLT I was encountering NaN (Not a Number) in my database. Here is the offending code.

<xsl:value-of select="number(string($RepairOrder/VehicleYear))"/>

This code can potentially return the NaN as a value because of the number function.

To solve this I used the test function in XSLT. My finally solution looks like this:

<Year>
   <xsl:choose>
      <xsl:when test="number(string($RepairOrder/VehicleYear)) 
!= number(string($RepairOrder/VehicleYear))
"> <xsl:number/> </xsl:when> <xsl:otherwise> <xsl:value-of select="number(string($RepairOrder/VehicleYear))"/> </xsl:otherwise> </xsl:choose> </Year>

 

Using the test I can determine that the resulting number NaN is not contained within my second express:

<xsl:when test="number(string($RepairOrder/VehicleYear)) 
!= number(string($RepairOrder/VehicleYear))
">

If it’s true I just set it to be the default number. Otherwise I pull the value of the number. To test this you can use the xslt test tool built into Visual Studio 2008/2010.

Wow that's backwards isn't it. Basically comparing NaN != NaN would = true and a Number != NaN would = false. My only conclusion here is that maybe because NaN isn't a comparable entity that saying (NonComparable != NonComparable) = true. Somewhat like trying to compare a null in SQL it isn't a valid comparable.

 

Looking at my example above, it's not very transparent either. So a better way would have been for me to further nest the number into a string and test it against 'NaN' like this:

<Year>
   <xsl:choose>
      <xsl:when test="string(number(string($RepairOrder/VehicleYear)) = 'NaN'">
<xsl:value-of select="number(string($RepairOrder/VehicleYear))"/> </xsl:when>
</xsl:choose>
</Year>

Xml, XSLT

Add comment




biuquote
  • Comment
  • Preview
Loading