[Home] [By Thread] [By Date] [Recent Entries]
On 5/25/07, Jesper Tverskov <jesper@xxxxxxxxxxx> wrote:
I have a feeling that my original code for UPC was right, as seen also in the "Check digit calculation" section here, http://en.wikipedia.org/wiki/Universal_Product_Code.
If you separate out the steps into variables then it becomes easier I think: <xsl:variable name="tokens" select="for $i in 1 to string-length(.) return xs:integer(substring(., $i, 1))" as="xs:integer+"/> <xsl:variable name="code" select="$tokens[position() ne last()]" as="xs:integer+"/> <xsl:variable name="check-digit" select="$tokens[last()]" as="xs:integer+"/> <xsl:variable name="odd" select="$code[position() mod 2 = 1]" as="xs:integer+"/> <xsl:variable name="even" select="$code[position() mod 2 = 0]" as="xs:integer+"/> <xsl:variable name="calc" select="(10 - ((sum($odd) * 3) + sum($even)) mod 10) mod 10" as="xs:integer"/> <improved tokens="{$tokens}" code="{$code}"
check-digit="{$check-digit}" calc="{$calc}">
<xsl:if test="$calc ne $check-digit">UPC not legal</xsl:if>
</improved>For this input: <test> <upc>639382000393</upc> <upc>036000291452</upc> </test> It returns: <improved tokens="6 3 9 3 8 2 0 0 0 3 9 3" code="6 3 9 3 8 2 0 0 0 3
9" check-digit="3"
calc="3"/>
<improved tokens="0 3 6 0 0 0 2 9 1 4 5 2" code="0 3 6 0 0 0 2 9 1 4
5" check-digit="2"
calc="2"/>The second test is taken from the example on wikipedia. cheers andrew
|

Cart



