简体   繁体   中英

How to retrieve 0 as the first number in C#

scenario:
I have a database having a record 001234 and I am calling it with cmd.executescaler(); into a int variable. The problem is when I retrieve the saved data ( 001234 ) data from that variable it gives only 1234 . 00 in 001234 are important, this was the problem first coming in db where sql omits the first zero's then I changed the datatype to nvarchar which works, how I can retrieve the data on the form exactly 001234 .

Note: I cannot take the data into string as I have to also apply some calculations on them.

using Sql Server visual studio 2010 c#

Hope it is clear not vague. If you need more information tell me. Thanks in advance.

Numeric datatype don't have and can't have leading zeros. So the only way to have leading zeros is to store the value as a string.

However, this is just a matter of formatting the output that is shown to the user. You can read the database value into an int variable, do your calculations and when showing the value, you can do:

string displayValue = String.Format("{0:D6}", intValue);

and show the value of displayValue .

If you want to work on the Code side :

string displayValue = String.Format("{0:D6}", intValue);

If you want to work on the DB side you need a Pad function that allows to write this kind of query:

SELECT dbo.PadString ('8', '0', 5)
->Result: 00008

SELECT dbo.PadString ('abc', '*', 12)
->Result: *********abc

SELECT dbo.PadString ('abc', '0', 7)
->Result: 0000abc

Create a function in T-SQL

CREATE FUNCTION [dbo].[PadString] 
  (@Seq varchar(16),
   @PadWith char(1),
   @PadLength int
  ) 
RETURNS varchar(16) AS

BEGIN 
  declare @curSeq varchar(16)

  SELECT @curSeq = ISNULL(REPLICATE(@PadWith, @PadLength - len(ISNULL(@Seq ,0))), '') + @Seq

  RETURN @curSeq
END

The reason SQL does this is because 001234 = 1234 in any number format no matter what type it is. As a "Dirty" solution you could cast it as an int which will give you 1234, perform your calculations and then cast your answer back to string adding the leading zeros.

int myValue = Int32.Parse("001234");
int myAnswer = myValue * 2;

string myAnswerString = "00" + myAnswer.ToString();

The best way to go though would be to format your string as suggested by @Thorsten Dittmar. If possible, do not store numeric values in the database as varchar to begin with, however I know that this is sometimes a requirement, but the I cannot see the point on doing calculations on those values.

If those leading zeros have some meaning and can't be left out, conversion can be done:

            int number = 0;
            string strNumber = (string)cmd.ExecuteScalar();
            if(int.TryParse(strNumber, out number))
            {
                // process number

                // if you want some output to be formatted with leading 
                // zeros you can use PadLeft method
                int totalNumberOfDigits = 6;
                string strResult = number.ToString().PadLeft(totalNumberOfDigits, '0');
            }

you can use string.PadLeft() in c# after retrieving your number, as you have fixed length numbers

example from msdn,

string str = "forty-two";
char pad = '.';

Console.WriteLine(str.PadLeft(15, pad));    // Displays "......forty-two".
Console.WriteLine(str.PadLeft(2, pad));     // Displays "forty-two".

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