변수를 기준으로 소수점 이하 자리가있는 XPath 형식 수는?
문제
소수점의 수가 특정 장소에있는 XML 문서가 있습니다. xs:decimal
IS는 형제 노드에 보관해야합니다. 나는 현재 이것을 통해 이것을 출력하는 간단한 방법을 찾기 위해 고군분투하고 있습니다. format-number
기능.
나는 다른 기능으로 그림 문자열을 만들 수 있지만, 이것은 비교적 간단하고 일반적인 작업이어야하는 (적어도 IMO)가되어야하는 것에 대해 끔찍한 일을합니다.
예 : 내가 현재하고있는 일은 다음과 같습니다.
<xsl:value-of
select="format-number(myNode/DecimalValue,
concat('#0.',
string-join(for $i in 1 to myNode/DecimalPlaces return '0'))"
/>
더 좋은 방법이 있습니까?
해결책
아주 좋은 질문! 그것은 보통, 나는 대답을 모른다는 것을 의미하지만, 나는 이것이 나에게도 고통이기 때문에 다른 사람이하기를 바랍니다.
어쨌든, 나는 약간의 검색을했고 나는 round-half-to-even
함수는 트릭을 수행 할 수 있습니다 (http://www.xqueryfunctions.com/xq/fn_round-half-to-even.html)
코드는 다음과 같습니다.
<xsl:value-of
select="
round-half-to-even(
myNode/DecimalValue
, myNode/DecimalPlaces
)
"
/>
이제 약간의 탄젠트를 위해 꺼짐 : XSLT 1.1 이하 및 XPath 1을 사용하는 사람들의 경우 다음을 사용할 수 있습니다.
<xsl:value-of
select="
concat(
substring-before(DecimalValue, '.')
, '.'
, substring(substring-after(DecimalValue, '.'), 1, DecimalPlaces -1)
, round(
concat(
substring(substring-after(DecimalValue, '.'), DecimalPlaces, 1)
, '.'
, substring(substring-after(DecimalValue, '.'), DecimalPlaces+1)
)
)
)
"
/>
물론이 코드는입니다 더 나쁜 원본보다는 XPath 1에 대한 원래 질문을 해결하는 방법을 알고 있고 이것보다 더 나은 아이디어를 가지고 있다면, 나는 그것을 듣고 싶습니다. (점점 더 자주, 나는 세상이 XML을 완전히 건너 뛰고 즉시 JSON으로 옮겼기를 바랍니다)
다른 팁
<!-- use a generous amount of zeros in a top-level variable -->
<xsl:variable name="zeros" select="'000000000000000000000000000000000'" />
<!-- …time passes… -->
<xsl:value-of select="
format-number(
myNode/DecimalValue,
concat('#0.', substring($zeros, 1, myNode/DecimalPlaces))
)
" />
템플릿으로 추상화 할 수 있습니다.
<!-- template mode is merely to prevent collisions with other templates -->
<xsl:template match="myNode" mode="FormatValue">
<xsl:value-of select="
format-number(
DecimalValue,
concat('#0.', substring($zeros, 1, DecimalPlaces))
)
" />
</xsl:template>
<!-- call like this -->
<xsl:apply-templates select="myNode" mode="FormatValue" />
이름이 지정된 템플릿을 만들고 호출 할 때 XSLT 컨텍스트 노드를 사용할 수도 있습니다. 입력 문서에 약간 의존하며 이것이 가능하다면 필요합니다.
<xsl:template name="FormatValue">
<!-- same as above -->
</xsl:template>
<!-- call like this -->
<xsl:for-each select="myNode">
<xsl:call-template name="FormatValue" />
</xsl:for-each>