Sergei Morozov
Sergei Morozov

Reputation: 622

Casting strings to numbers using XSLT

There is a task to output some data taken from database using XSLT. The application current locale is ru_RU, so decimal separator is comma. It looks like

<data>
  <row>
    <date value="28.04.2010"/>
    <clicks value="281"/>
    <depth value="1,7"/>
  <row>
  <row>
    <date value="29.04.2010"/>
    <clicks value="15"/>
    <depth value="3"/>
  <row>
<data>

It’s needed to format "depth" value as decimal number: 1,70 and 3,00. When I try to transform the value ising:

<xsl:value-of select="format-number(number(depth/@value)), '##.##'"/>

I get NaN because XSLT-processor doesn’t consider comma as a decimal separator when casting attribute value to number.

It helps somehow when I manually "translate" the source string from "decimal comma" format to "decimal point" one

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

but it looks rather ugly.

Is there any more correct and centralized way to tell the processor that comma sign is a decimal separator?

Upvotes: 3

Views: 11443

Answers (2)

Jan Willem B
Jan Willem B

Reputation: 3806

There is no more correct or centralized way. The way I do this is to pre-process the XML file with a special xslt which transforms the numbers the way you do it too.

Upvotes: 2

baol
baol

Reputation: 4358

Have you tried using the locale parameter of format-number? (format-number has a third optional parameter)

Upvotes: 1

Related Questions