Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT format-number with comma

Tags:

format

xml

xslt

I'm trying to format this and other elements alike, so it would look like this 2,590:

<Add_Amount>2,59</Add_Amount>

Doing it like this:

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

....

    <xsl:value-of select="translate(format-number(Add_Amount, '#.###,000', 'dkk'), ',', '.')" />

And the output comes out NaN. Any help is greatly appreciated.

Thanks.

//Daniel

like image 738
Daniel Falkner Avatar asked Sep 21 '10 09:09

Daniel Falkner


People also ask

What is Number () in XSLT?

Specifies the format pattern. Here are some of the characters used in the formatting pattern: 0 (Digit) # (Digit, zero shows as absent)

How do you round off numbers in XSLT?

For example : 9.2750 rounds up to 9.28, but 9.2850 rounds down to 9.28 . 9.2950 rounds up to 9.30, but 9.3050 rounds down to 9.30. Here is the XSLT I am using: <xsl:value-of select="format-number($number,'##.

How do I format XSLT?

The format date on XSLT Technique uses a template dealing with Gregorian Time and Internationalization. The parameter for this date function is a picture string that encloses code in square brackets(D[07]). The name attributes declare date format or default date. It should be declared only once.

How do you do division in XSLT?

Accordingly, XPath and XSLT use the string "div" for division. Lines E and F show how parentheses have the same effect on operator precedence that they have in normal math notation: without them, multiplication happens before addition, so that 4 + 3.2 * 11 = 4 + 35.2.


2 Answers

Use:

format-number(translate(., ',','.'), '#.###,000', 'd')

This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

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

 <xsl:template match="/">
   <xsl:value-of select=
   "format-number(translate(., ',','.'), '#.###,000', 'd')"/>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<Add_Amount>2,59</Add_Amount>

produces the wanted result:

2,590

The problem with your code is that 2,59 isn't a valid number and must be converted to such, before passing this as the first argument of format-number().

like image 78
Dimitre Novatchev Avatar answered Oct 16 '22 03:10

Dimitre Novatchev


The extra call to translate() in Dimitre Novatchev's answer seems unnecessary. The use of <xsl:decimal-format> should be enough, like this:

<xsl:decimal-format name="euroFormat" decimal-separator="," grouping-separator="."/>
<xsl:value-of select="format-number(text(), '###.###,00', 'euroFormat')"/>
like image 32
Bart Kummel Avatar answered Oct 16 '22 02:10

Bart Kummel