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
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 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.
Related
I'm making a console application for IP assignment where a user simply enters the number of networks, the number of hosts per network and the initial network IP address, and this generates the full IP assignment table.
My biggest issue right now is that say I have a string with "172.16.0.0".
I want to grab the 0 at the end, convert it to an int, add a certain number of hosts (say, 0 + 512), and if it goes over 255, I want it to instead grab the previous 0 and replace it with a 1 instead then test it again. But I'm mostly having issues with replacing the numbers in the initial string. Since strings aren't mutable, I obviously have to make a new string with the change, but I can't see how to do this.
I've so far tried finding the index where the change will be made using the string.split function and indexof and making that an int variable called datIndex. Then I change the "172.16.0.0" string to a character array, then tried swapping the character in the previously defined index, however this limits me to a single character, which wouldn't work for a number with more than one digit. Also tried using stringbuilder but the stringbuilder object seems to be a char type so I end up in the same place, can't equal the value in the index I want to change to the new number.
string test = "172.16.0.0";
int datIndex = test.IndexOf(test.Split('.')[2]);
char[] c = test.ToCharArray();
c[datIndex] = '201'; //Not possible because more than one digit
//Also tried the following
datIndex = test.IndexOf(test.Split('.')[2]);
StringBuilder sb = new StringBuilder(test);
sb[datIndex] = '201'; //Cannot implicitly convert type string to char
string temp2 = sb.ToString();
test = temp2; //Changed string
In this example, I'd like to change the penultimate "0" in the "172.16.0.0" string to a "201" (this number would be obtained by a sum of two numbers so ideally they'd both first be integers).
However with both methods I've tried, I can't fit a number bigger than one digit into that index.
This is maybe what you are looking for:
string ip = "127.16.0.0";
string ipNumbers = ip.Split('.');
int a = int.Parse (ipNumbers[0]);
int b = int.Parse (ipNumbers[1]);
int c = int.Parse (ipNumbers[2]);
int d = int.Parse (ipNumbers[3]);
//now you have in a,b,c and d all the ip numbers, do the math with them and then do this:
ip = $"{a}.{b}.{c}.{d}";
I am trying to figure out how to format a string to a specific pattern.
When a user is entering their employee id number, they often get confused on what is expected from them. Because they are often told that their employee id is either a 5 digit or 4 digit number depending on when they were hired.
For example, my employee id number is E004033 but for most of our systems, I just have to enter 4033 and the system will find me.
We are trying to add this to one of our custom pages. Basically what I want to do is format a string to always look like E0XXXXX
So if they enter 4033 the script will convert it to E004033, if they enter something like 0851 it will convert it to E000851 or if they enter 11027 it will convert it to E011027
Is there a way basically add padding zeros and a leading E if they are missing from the users input?
You can simply:
var formattedId = "E" + id.PadLeft(6, '0');
To remove an existing leading E(s)
var text = "E" + val.TrimStart(new[] {'E'}).PadLeft(6, '0');
Make sure the user's input is an integer, then format to 6 spaces using String.Format.
int parsedId;
bool ok = int.TryParse(id, out parsedId);
if (ok)
{
return String.Format("E{0:000000}", parsedId);
}
I am trying to insert an entry into a database:
mySqlCommand.CommandText = "INSERT INTO table_name (col1, col2) values (#number, #word);";
mySqlCommand.Parameters.Add("#number", MySqlDbType.Int32);
mySqlCommand.Parameters.Add("#word", MySqlDbType.VarChar);
mySqlCommand.Parameters["#number"].Value = 0110;
mySqlCommand.Parameters["#word"].Value = "Hello";
However when I get it back out, it's stored as 110 instead of 0110. How can I get it to recognise the leading 0?
Well your datatype is integer. when 0110 is cast to integer it becomes 110.
To achieve your goal you need to set its datatype as varchar both in table and
MySqlDbType.Int32 to MySqlDbType.VarChar.
Hope this will help you.
There is nothing like leading 0 in int. however if u want to store the leading 0 then you can convert data type of that field to Varchar..
or by programmatically you can also pad 0 in any variable but again it will be converted to string.
Like this
int Anynumber= 5;
string AnynumberWithZero = string.Format("{0}", Anynumber.ToString().PadLeft(2, '0'));
Result will be"05"
I need to convert a string in the database of patients to a int to create a new patient ID.
In the Hospital database, the patient ID is a STRING, not an integer. It is of the form p99. To create a new ID, I need to take out the p, convert to an integer, add 1, then put a 0 in if the value is less than 10, then add back the p.
I am using Microsoft visual studio and C#.
How would I go about this? Any help would be greatly appreciated!
You can use string.Substring Method and Int32.TryParse method.
String.Substring Method (Int32)
Retrieves a substring from this instance. The substring starts at a
specified character position.
Int32.TryParse Method (String, Int32)
Converts the string representation of a number to its 32-bit signed
integer equivalent. A return value indicates whether the conversion
succeeded.
string patientId = "p99";
int id;
if (Int32.TryParse(patientId.Substring(1), out id))
{
patientId = string.Format("p{0}{1}", id < 10 ? "0" : string.Empty, id);
MessageBox.Show("Patient Id : " + patientId);
}
else
{
MessageBox.Show("Error while retrieving the patient id.");
}
You can use int.Parse() (MSDN) to convert a string to an integer.
You can write a simple routine to do this.
Assuming there is always a leading 'p' you can just do sID = sID.substring(1) to remove the first character.
Then you can use Int ID = Int16.Parse(sID) to convert to an Int (16-bit in this case). If you need 32-bit, use Int32.Parse
then ID++ or ID = ID+1 to increment by one.
Next, you need to convert back to a string with sID = ID.ToString()
Finally, do some string manipulation to test the length, add the leading '0' if length = 1, and the leading 'p'.
I'm saving a numeric value into a datatable cell (no datatype for the cell has been explicitly declared), then later retrieving that data and trying to format it into a string. Problem is that nothing I've tried will properly format the string.
50000 --> 50,000
I've tried (where r is the row in a loop):
String.Format("{0:0,0}", r["columnName"])
r["columnName"].ToString("n0")
And several variations without any luck. Most of the time I just get the number without the comma.
String.Format("{0:0,0}",int.Parse(r["columnName"].ToString()))
Probably not the most elegant solution, but you could just iterate backwards from the tail-end of the string (or from the decimal point) adding a comma every three characters until you run out.
It might be helpful to have more context for what you're trying to do, but here is an example of getting a value out of a DataTable and then formatting it as desired.
DataTable dt = new DataTable();
dt.Columns.Add( "cellName", typeof( double ) );
dt.Rows.Add( 123.45 );
string val = ( (double)dt.Rows[0]["cellName"] ).ToString( "N" ); // val = "123.45"
I'm explicitly casting the value back to a double before calling ToString. You could also call string.Format on that value instead of ToString and it should work just as well.
EDIT: If you're storing the value as a string and then want to format it, use this:
string val = ( double.Parse( dt.Rows[0]["cellName"] ) ).ToString( "N" );
This does assume that the value is parsable though (i.e. isn't null).
The problem with these methods is that depending on the structure of the underlying table that field may be null. If you try to cast a null value held as an object (in the DataTable) to string,integer, decimal, or what have you... your app will blow up 100% of the time. Unless your DataSet is a strongly typed data set you will always want to do this error checking. As a matter of fact, writing a small data reading class to read string, decimals, date times, integers, whatever... is a must in any Data access operations having to do with Database....
So here is more error proof approach which idealy should be wrapped in a helper method as shown here:
public static string GetFormatedDecimalString(DataRow row, string columnName, string format)
{
string ColumnNameStringValue = String.Empty;
decimal ColumnNameValue = Decimal.Zero;
if( row[columnName) == DBNull.Value )
{
ColumnNameValue = Decimal.Zero;
}
else
{
ColumnNameStringValue = row[columnName].ToString();
if( ! Decimal.TryParse(ColumnNameStringValue, out ColumnNameValue )
{
ColumnNameValue = Decimal.Zero;
}
// if the if statement evaluated to false the ColumnNameValue will have the right
// number you are looking for.
}
return ColumnNameValue.ToString(format);
}
passing "N" or "{0:0,0}" as the format string will work just fine.