41

I want to convert a string value in xslt to an integer value. I am using xslt 1.0, so i can't use those functions supported in xslt 2.0. Please help.

8
  • 2
    Could you provide a sample input XML document, a sample XSLT and possibly describe the desired output? Aug 12, 2009 at 12:33
  • you can take any sample file and convert the string to integer. I guess no need for the samples
    – Kapil
    Aug 12, 2009 at 12:36
  • But how do you want your output to look like? And what do you want to do with that number? It is very hard to help without knowing what you are trying to achieve. Aug 12, 2009 at 12:37
  • 2
    So could you show a short sample? Aug 12, 2009 at 12:42
  • 3
    "not working" is perhaps the best way to avoid getting a valid answer. If number() isn't doing what you want, then it seems that you're trying to do something that doesn't really require a number. So, as divo asked, provide sample input, sample output, and the XSLT that you're using. And do it in your question, formatted as code, not in a comment.
    – kdgregory
    Aug 12, 2009 at 12:53

2 Answers 2

70

Adding to jelovirt's answer, you can use number() to convert the value to a number, then round(), floor(), or ceiling() to get a whole integer.

Example

<xsl:variable name="MyValAsText" select="'5.14'"/>
<xsl:value-of select="number($MyValAsText) * 2"/> <!-- This outputs 10.28 -->
<xsl:value-of select="floor($MyValAsText)"/> <!-- outputs 5 -->
<xsl:value-of select="ceiling($MyValAsText)"/> <!-- outputs 6 -->
<xsl:value-of select="round($MyValAsText)"/> <!-- outputs 5 -->
2
  • 1
    In XPath 1.0, if a function (like floor(), ceiling() or round()) expects a number data type argument, then it's going to implicitly cast its argument with number() function.
    – user357812
    Jan 25, 2011 at 21:56
  • So my "number($MyValAsText)" is superfluous? Well, let's save those bits then! Thanks for the tip Alejandro. I've gotten bit by not casting enough times in XSLT that I generally cast too often (case in point). Jan 26, 2011 at 23:33
35

XSLT 1.0 does not have an integer data type, only double. You can use number() to convert a string to a number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.