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'.
Related
I have Script2 which has int restaurant1Current, along with several other variables with similar names. On another script, I'm trying to parse the value of restaurant1Current using this code. category is a string with the value of "restaurant1".
string currentStringBuffer = "Script2." + category + "Current";
int currentNumber = int.Parse(currentStringBuffer);
I want to be able to use the same code as I change the value of category hence the need to parse it using a string instead of referencing the variable directly. Is this the correct syntax or am I missing something? As is the code tells me "The input string is not in the correct format" but when debugging it shows that the string contains the value "Script2.restaurant1Current" which again is an int. So why wouldn't I be able to parse the value to currentNumber in the next line?
public Enum Categories{
Restauraunt,
Grocer,
Bank
}
Enum stands for enumeration, it is a numbered list. with this particular enum,
Categories.Bank =2; so you can call or assign.
something.category=2;
or
int rando = Categories.Bank
I have an string AssetNumber that have the following format C100200.
so i need to do the folloiwng:-
Get all the characters after the first (e.g. 100200 using above example)
Convert the substring to integer
Return the integer + 1
but I do not know how to use the sub-string to get all the characters after the first char, and how to convert string into int? Any help on this will be appreciated.
var result = Int32.Parse("C100200".Substring(1)) + 1;
If you would like to have default value, if you can't parse current string:
int result;
if (!Int32.TryParse("sdfsdf".Substring(1), out result)) {
result = 42;
}
result+=1;
I have a situation where I need to prefix a zero to an integer.
Initially I have string which has 12 chars, first 7 are alphabets and 5 are numeric values.
The generated string some times have a zero at starting position of numeric values. for example ABCDEF*0*1234, and my scenario is to generate a range of strings from the generated string. Suppose I want to generate a range (assume 3 in number), so it would be ABCDEF01235, ABCDEF01236, ABCDEF01237.
When I try to convert a string which has a 0 (as shown above) to int, it returns only 1234.
Is there any way to do this, without truncating zero?
You can use PadLeft to expand a given string to a given total length:
int num = 1234;
Console.WriteLine(num.ToString().PadLeft(5, '0')); // "01234"
int num = 1234;
Console.WriteLine(num.ToString("D5")); // "01234"
No with int.
You have to use string to concatenate the parsed number and the 0
int num = 1234;
Console.WriteLine($"{num:d5}");
I think you can use string.Format
int num = 1234;
Console.WriteLine(string.Format("0{0}", num));
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.
I have a numeric string like this 2223,00. I would like to transform it to 2223. This is: without the information after the ",". Assume that there will be only two decimals after the ",".
I did:
str = str.Remove(str.Length - 3, 3);
Is there a more elegant solution? Maybe using another function? -I donĀ“t like putting explicit numbers-
You can actually just use the Remove overload that takes one parameter:
str = str.Remove(str.Length - 3);
However, if you're trying to avoid hard coding the length, you can use:
str = str.Remove(str.IndexOf(','));
Perhaps this:
str = str.Split(",").First();
This will return to you a string excluding everything after the comma
str = str.Substring(0, str.IndexOf(','));
Of course, this assumes your string actually has a comma with decimals. The above code will fail if it doesn't. You'd want to do more checks:
commaPos = str.IndexOf(',');
if(commaPos != -1)
str = str.Substring(0, commaPos)
I'm assuming you're working with a string to begin with. Ideally, if you're working with a number to begin with, like a float or double, you could just cast it to an int, then do myInt.ToString() like:
myInt = (int)double.Parse(myString)
This parses the double using the current culture (here in the US, we use . for decimal points). However, this again assumes that your input string is can be parsed.
String.Format("{0:0}", 123.4567); // "123"
If your initial value is a decimal into a string, you will need to convert
String.Format("{0:0}", double.Parse("3.5", CultureInfo.InvariantCulture)) //3.5
In this example, I choose Invariant culture but you could use the one you want.
I prefer using the Formatting function because you never know if the decimal may contain 2 or 3 leading number in the future.
Edit: You can also use Truncate to remove all after the , or .
Console.WriteLine(Decimal.Truncate(Convert.ToDecimal("3,5")));
Use:
public static class StringExtensions
{
/// <summary>
/// Cut End. "12".SubstringFromEnd(1) -> "1"
/// </summary>
public static string SubstringFromEnd(this string value, int startindex)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Substring(0, value.Length - startindex);
}
}
I prefer an extension method here for two reasons:
I can chain it with Substring.
Example: f1.Substring(directorypathLength).SubstringFromEnd(1)
Speed.
You could use LastIndexOf and Substring combined to get all characters to the left of the last index of the comma within the sting.
string var = var.Substring(0, var.LastIndexOf(','));
You can use TrimEnd. It's efficient as well and looks clean.
"Name,".TrimEnd(',');
Try the following. It worked for me:
str = str.Split(',').Last();
Since C# 8.0 it has been possible to do this with a range operator.
string textValue = "2223,00";
textValue = textValue[0..^3];
Console.WriteLine(textValue);
This would output the string 2223.
The 0 says that it should start from the zeroth position in the string
The .. says that it should take the range between the operands on either side
The ^ says that it should take the operand relative to the end of the sequence
The 3 says that it should end from the third position in the string
Use lastIndexOf. Like:
string var = var.lastIndexOf(',');