How to Prefix '0' (zero) to integer value - c#

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));

Related

Convert string to unicode in C#?

How can I get the unicode values (from the code column) if I have the string?
For example, for passing the empty space " " I would like to get the value U+0020.
I found this approach:
byte[] asciiBytes1 = Encoding.ASCII.GetBytes(" ");
But this returns me the value from the decimal column.
If value is your decimal value:
string code = $"U+{value.ToString ("X4")}";
will give you what you want.
(X means hex, 4 means pad to 4 digits)

C# Converting Problems with String Array to Int Array

I`m working with C# and I have a problem at converting a string array to a int array.
First I created a string number with the Console
Console.WriteLine("Geben Sie die Nummer ein:");
string wert = Console.ReadLine();
Then I converted the string to a array
char[] wertarray = wert.ToCharArray();
wertarray1 = new string(wertarray);*
And now comes the problem. I want to convert the string array to a int array, but e.g. for string wertarray1[0]=1, the int array has the value 49.
int wertarray2 = Convert.ToInt16(wertarray1[0]);
Normal the Int value should be 1, but I don`t know where the problem is.
I tried the solutions for "convert a string array to a int array" from this forum, but i still had the problem that the int value get a strange number.
I´m looking forward for help.
Thanks :-).
Convert.ToInt16(Char) takes the numeric value of the char (i.e. its Unicode code-point value) and returns that number. While you might think Convert.ToInt16('1') should return 1, consider what would happen if you tried Convert.ToInt16('#') for example.
Use Int16.Parse (or TryParse) to actually parse a string to numbers. As you're working with individual characters to represent 0-9 you might as well do it using simple arithmetic without the need to call any Parse function:
String line = Console.ReadLine();
List<Int16> numbers = new List<Int16>( line.Length );
foreach(Char c in line) {
Int16 charValue = (Int16)c;
if( charValue < 48 || charValue > 57 ) throw new Exception("char is not a digit");
Int16 value = charValue - 48;
numbers.Add( value );
}
Answers provided already explain your problem and provide solution too.
In general, you can convert the char to string and parse them to integer (not the best performance though).
If you have all numeric string
var numStr = "136";
var numbers = numStr.Select(n => int.Parse(n.ToString())).ToList(); // {1, 3, 6}
If your string contains non numbers too
var mixStr = "1.k78Tj_n";
int temp;
var numbers2 = new List<int>();
mixStr.ToList().ForEach(n =>
{
if (int.TryParse(n.ToString(), out temp))
numbers2.Add(temp);
}); //{ 1, 7, 8 }
You're getting the Unicode code point value of the characters in your input stream -- 49 is the unicode value for the character 1.
If you want to convert a unicode character that is a digit to the numeric value of that digit, you can use System.Globalization.CharUnicodeInfo.GetDecimalDigitValue(char c):
var wertarray2 = wert.Select(c => (short)CharUnicodeInfo.GetDecimalDigitValue(c)).ToArray();
This handles all digits (including superscripted numbers) not just the standard ASCII digits.

Convert integer number to three digit

I have an integer variable .if its 1-9 it only displays as "1" or "9", I'm looking to convert the variable to save as 3 digits, ie. "001", or "009", etc. any ideas?
I am using C#,ASP.Net
use
int X = 9;
string PaddedResult = X.ToString().PadLeft (3, '0'); // results in 009
see MSDN references here and here.
What about
var result = String.Format("{0:000}", X);
var result2 = X.ToString("000");
int i = 5;
string tVal=i.ToString("000");
From: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#DFormatString
The "D" (or decimal) format specifier converts a number to a string of decimal digits (0-9), prefixed by a minus sign if the number is negative.
The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier.
Like:
int value;
value = 12345;
Console.WriteLine(value.ToString("D"));
// Displays 12345
Console.WriteLine(value.ToString("D8"));
// Displays 00012345
value = -12345;
Console.WriteLine(value.ToString("D"));
// Displays -12345
Console.WriteLine(value.ToString("D8"));
// Displays -00012345
int i = 5;
string retVal = i.ToString().PadLeft(3, '0');
you can use this code also
int k = 5;
string name = $"name-{k++:D3}.ext";

What does Int32.Parse do exactly?

I am just beginning to learn C#. I am reading a book and one of the examples is this:
using System;
public class Example
{
public static void Main()
{
string myInput;
int myInt;
Console.Write("Please enter a number: ");
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);
Console.WriteLine(myInt);
Console.ReadLine();
}
}
When i run that and enter say 'five' and hit return, i get 'input string not in correct format' error. The thing i don't understand is, i converted the string myInput to a number didn't i? Microsoft says that In32.Parse 'Converts the string representation of a number to its 32-bit signed integer equivalent.' So how come it doesn't work when i type the word five? It should be converted to an integer shouldn't it... confused. Thanks for advice.
'five' is not a number. It's a 4-character string with no digits in it. What parse32 is looking for is a STRING that contains numeric digit characters. You have to feed it "5" instead.
The string representation that Int32.Parse expects is a sequence of decimal digits (base 10), such as "2011". It doesn't accept natural language.
What is does is essentially this:
return 1000 * ('2' - '0')
+ 100 * ('0' - '0')
+ 10 * ('1' - '0')
+ 1 * ('1' - '0');
You can customize Int32.Parse slightly by passing different NumberStyles. For example, NumberStyles.AllowLeadingWhite allows leading white-space in the input string: " 2011".
The words representing a number aren't converted; it converts the characters that represent numbers into actual numbers.
"5" in a string is stored in memory as the ASCII (or unicode) character representation of a 5. The ASCII for a 5 is 0x35 (hex) or 53 (decimal). An integer with the value '5' is stored in memory as an actual 5, i.e. 0101 binary.

Formatting values

Hi i have a int example as 3 i need to format it as 003 . is the only way is convert to a string and concat and convert back ?
I guess this is what you want:
int n = 3;
string formatted = n.ToString("000");
Alternatively:
string formatted = String.Format("{0:000}", n);
More info here.
You can apply the .ToString("000"); method.
Debug.WriteLine(3.ToString("000"));
You can parse the resulting string value by using int.Parse or int.TryParse:
Debug.WriteLine(int.Parse("003"));
See Custom Numeric Format Strings
If it's an int object, the leading zeros will always be removed, regardless if you convert it to a string and back.
use the pad functionint i = 1;
i.ToString().PadLeft(3, '0');

Categories