开发者

Not able to calculate in XSLT after switching the PHP locale

To get "," instead of "." as a decimal point, I set the locale via setlocale("de_DE");.

When I now transform an XSLT stylesheet that contains a calculation like:

<xsl:variable name="a">
   <xsl:choose>
      <xsl:when test="$someboolean">
         <xsl:value-of select="0.5"/>
      </xsl:when>
      <xsl:otherwise>
         <xsl:value-of select="0"/>
      </xsl:otherwise>
   </xsl:choose>
</xsl:variable>
<xsl:value-of select="$a + 2"/>

returns NaN.

<xsl:value-of select="$a"/>

brings me a "0,5", which is good. But the NaN as a result of $a+2 is not what I expected.

Why is $a contverted to text? Am I doing the calculation wrong? Is this behaviour a bug?


To make myself clear. Is this th开发者_如何学Goe right behaviour of XSLT?

<xsl:variable name="a"><xsl:value-of select="0.5"/></xsl:variable>
<xsl:value-of select="$a"/> <!-- gives 0,5 --> 
<xsl:value-of select="$a + 2"/> <!-- gives NaN --> 
<xsl:variable name="b" select="0.5"/> 
<xsl:value-of select="$b"/> <!-- gives 0,5 --> 
<xsl:value-of select="$b + 2"/> <!-- gives 2,5 -->

The complete testing code:

<?php
printf("%.1f",0.5);  // gives 0.5
setlocale (LC_ALL, 'de_DE.utf8', 'de_DE@euro', 'de_DE', 'deu_deu', 'deu', 'de', 'ge');
printf("%.1f",0.5);  // gives 0,5

$xml = new DOMDocument;
$xml->loadXML('<a>a</a>');

$xsl = new DOMDocument;
$xsl->substituteEntities = TRUE;
$xsl->loadXML('
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:template match="/">
            <xsl:variable name="a"><xsl:value-of select="0.5"/></xsl:variable>
            <xsl:value-of select="$a"/>      <!-- gives 0,5 -->
            <xsl:value-of select="$a + 2"/>  <!-- gives NaN -->

            <xsl:variable name="b" select="0.5"/>
            <xsl:value-of select="$b"/>      <!-- gives 0,5 -->
            <xsl:value-of select="$b + 2"/>  <!-- gives 2,5 -->
        </xsl:template>
    </xsl:stylesheet>');

$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl);

echo $proc->transformToXML($xml);

?>


There are constructs provided in XSLT to do this:

  1. Declare a decimal-format with the "," as the decimal separator.
  2. Use the format-number function and specify the declared decimal-format.

Note: decimal-format has to be declared at the top level of the stylesheet.

<xsl:decimal-format name="european" decimal-separator=',' grouping-separator='.' />

When you want your numbers formatted with "," use format-number with the decimal-format:

<xsl:value-of select="format-number($a+2, '###.###,00', 'european')"/>


What you are mixing is output format and numerical value. The xsl expressions are not localized, therefore the decimal comma is not seen as a valid part of the value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜