0

I want to save products serial numbers, I created a table

dbo.tStock
productType tinyint,
IdProduct int, 
ItemTypeNum tinyint, 
FirstSNum  nchar (20), 
LastSNum   nchar (20), 
TotalQty   bigint

when the user insert the totalQty and the first Serial Number FirstSNum the application should calculate the last serial number in squence.
In my page i used javascript function:

function Calculate() {
            var txt1 = document.getElementById('<%= txtTotalQty.ClientID%>').value
            var txt2 = document.getElementById('<%= txtFirstserial.ClientID%>').value
            if (txt1 != '' && txt2 != "")
                document.getElementById('<%= txtLastSerial.ClientID%>').value = 
                eval((parseFloat(txt1)-1 + parseFloat(txt2)))
        }

The problem is when the serial number start with zero (leading zero) I got a wrong calculation,eg:
totalQty: 100
Firstserial: 01000
LastSerial: 1099 (WRONG) it should be=01099
I'm using ASP.NET C#,
any idea? I appreciate any efforts ;-)

Rob Levine
  • 40,328
  • 13
  • 85
  • 111
Salahaldin
  • 92
  • 4
  • 15

1 Answers1

0

eval((parseFloat(txt1)-1 + parseFloat(txt2)))

You don't need eval(). Just add the values.

parseFloat() does exactly what it says on the tin. It converts a string "01000" into a number: 1000. So you end up with just a number, and numbers don't have leading zeroes.

If you want to zero-pad the resulting number, you need to do that yourself.

("00000" + (parseFloat(txt1)-1 + (parseFloat(txt2))).toString()).substr(-5,5);

Do your calculation, convert it to a string, prepend "00000" to it and then take the right-most five characters.

Andrew Leach
  • 12,945
  • 1
  • 40
  • 47
  • thanks, The length of each SN should be 15 digits, I think _substr()_ used to replace an existing, So I used: zeropad(( (parseFloat(txt1)-1 + (parseFloat(txt2))).toString()),15) from the above link function pad(num, size) { var s = num+""; while (s.length < size) s = "0" + s; return s; } – Salahaldin Apr 24 '12 at 15:14
  • If you want fifteen digits, just use fifteen digits: `("000000000000000" + (parseFloat(txt1)-1 + (parseFloat(txt2))).toString()).substr(-15,15)`; – Andrew Leach Apr 24 '12 at 15:17