简体   繁体   中英

Increment number from a string

So one of the projects we have for one of our clients allows them to print checks. One of the fields that goes on the check is check number. Currently we are storing the check numbers(for reporting purposes) in a database as an int type.

The problem is that the client wants to increase the size of the check number to 20 digits. One of the features of the project is to auto assign check numbers to each check when printing multiple checks.

So for example they are printing 3 checks. They enter the starting check number as "100123" and then click an "Assign Check Numbers" button at witch point the first check to be printed gets the "100123" that was entered and each following check is given the same number incremented by one so the second check would get "100124", the third would get "100125" and so on.

The problem is that they want a 20 digit check number which is too big for any numerical data type. My only solution is to change the check number to string/varchar but that would break the "Assign Check Numbers" process for multiple checks since I can't increment the string to get the next number.

Any ideas on how I could implement such a requirement?

请使用BigIntegerdecimal ,因为两者的精度都超出了要求。

Actually the range of a ulong goes from 0 to 18,446,744,073,709,551,615 , which is 20 digits. I'm assuming there won't be any "negative" check numbers. So long as the first two numbers of the check are less than 17, you can do this:

ulong checkNumber = ulong.Parse(textCheckNumber);
checkNumber++;
string newCheckNumber = checkNumber.ToString();

If there is a possibility that the first two digits are greater than or equal to 17, then you can do this:

ulong checkNumber = ulong.Parse(textCheckNumber.SubString(2));
checkNumber++;
string newCheckNumber = textCheckNumber.SubString(0,2) + checkNumber;

You could use long . Its max value is 2(^64)-1 .

Thanks for all the feedback everyone.

Saving to the database as varchar should be fine. Here is what I came up with for the increment based on everyone's feedback.

string sampleNum = "01999999999999999997";

for (int i = 0; i < 5; i++)
{
    int first = int.Parse(sampleNum.Substring(0, 2));
    ulong rest = ulong.Parse(sampleNum.Substring(2));

    rest++;
    if (rest > 999999999999999999)
    {
        first++;
        rest = 0;
    }

    sampleNum = first.ToString().PadLeft(2, '0') + rest.ToString().PadLeft(18, '0');

    Console.WriteLine(sampleNum);
}

Here is what I got in the test:

01999999999999999998 
01999999999999999999 
02000000000000000000 
02000000000000000001 
02000000000000000002 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM