Skip to content

Instantly share code, notes, and snippets.

@shaunhey
Created March 11, 2013 14:56
Show Gist options
  • Save shaunhey/5134800 to your computer and use it in GitHub Desktop.
Save shaunhey/5134800 to your computer and use it in GitHub Desktop.
<html>
<head>
<script type="text/javascript">
var NONE = 0;
var PLUS = 1;
var MINUS = -1;
function calculateWeightedProduct(digit, weight, sign) {
var value = digit * weight;
var tens = Math.floor(value / 10);
value += sign * tens;
return value % 10;
}
function calculateFourDigitPriceCheckDigit(price) {
var checkDigit = 0;
checkDigit += calculateWeightedProduct(price[0], 2, MINUS);
checkDigit += calculateWeightedProduct(price[1], 2, MINUS);
checkDigit += calculateWeightedProduct(price[2], 3, NONE);
checkDigit += calculateWeightedProduct(price[3], 5, MINUS);
checkDigit *= 3;
return checkDigit % 10;
}
function calculateFiveDigitPriceCheckDigit(price) {
var checkDigit = 0;
checkDigit += calculateWeightedProduct(price[0], 5, PLUS);
checkDigit += calculateWeightedProduct(price[1], 2, MINUS);
checkDigit += calculateWeightedProduct(price[2], 5, MINUS);
checkDigit += calculateWeightedProduct(price[3], 5, PLUS);
checkDigit += calculateWeightedProduct(price[4], 2, MINUS);
checkDigit = (10 - (checkDigit % 10)) % 10;
if (checkDigit) {
for (var i = 0; i < 10; i++) {
if (calculateWeightedProduct(i, 5, MINUS) == checkDigit) {
checkDigit = i;
break;
}
}
}
return checkDigit;
}
function calculateCheckDigit() {
var priceTextBox = document.getElementById("price");
var checkDigitTextBox = document.getElementById("checkDigit");
if (priceTextBox.value.length == 4) {
checkDigitTextBox.value = calculateFourDigitPriceCheckDigit(priceTextBox.value);
} else if (priceTextBox.value.length == 5) {
checkDigitTextBox.value = calculateFiveDigitPriceCheckDigit(priceTextBox.value);
} else {
checkDigitTextBox.value = "";
}
}
</script>
</head>
<body>
<b>Price field check digit calculator</b><br>
This tool calculates the price check digit for UPC2/NSC2 barcodes with 4 and 5 digit price fields.<br><br>
Price:<br>
<input label="Price" type="text" id="price" size="5" maxlength="5" onkeyup="calculateCheckDigit()"><br><br>
Price Check Digit:<br>
<input type="text" id="checkDigit" size="1" readonly><br>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment