Number increment from string value - c#

I my application due to some reason I have two numbers in 5 digits.
The following code give you brief idea.
string s = "00001"; // Initially stored somewhere.
//Operation start
string id = DateTime.Now.ToString("yy") + DateTime.Now.AddYears(-1).ToString("yy") + s;
//Operation end
//Increment the value of s by 1. i.e 00001 to 00002
This can be done easily by convert the value of s to int and increment it by 1 but after all that I have to also store the incremented value of s in 5 digit so it will be "00002".
This think give me a pain...

use
string s = "00001";
int number = Convert.ToInt32(s);
number += 1;
string str = number.ToString("D5");
to get atleast 5 digits.
The "D" (or decimal) format specifier
If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier. If no
precision specifier is specified, the default is the minimum value
required to represent the integer without leading zeros.

This seems to work for me.
string s = "00001";
int i = Int32.Parse(s);
i++;
s = i.ToString("D" + s.Length);

So I think you want to know how to convert an int to a 5 digit string.
You can do this:
int i = 1;
string s = i.ToString("D5");
//s = "00001"
There are plenty of format examples here.

Use String.Format() to achieve this:
string str = String.Format({0:#####}, s);
Look here.

This works using the PadLeft function:
int i = 1; // Initially stored somewhere.
//Operation start
string id = DateTime.Now.ToString("yy") + DateTime.Now.AddYears(-1).ToString("yy") + i.ToString().PadLeft(5, '0');
//Operation end

Related

How to convert a double value to string without rounded [duplicate]

This question already has answers here:
Truncate Two decimal places without rounding
(24 answers)
Closed 7 years ago.
I have this variable:
Double dou = 99.99;
I want to convert it to a string variable, and the string should be 99.9.
I can do it like this:
string str = String.Format("{0:0.#}", dou);
But the value I got is: 100 which is not 99.9.
So how could I implement that?
PS: This question is marked as duplicated. Yes, they may have the same the solution (although I think that's a workaround), but from different viewpoints.
For example, if there is another variable:
Double dou2 = 99.9999999;
I want to convert it to string: 99.999999, so how should I do? Like this:
Math.Truncate(1000000 * value) / 1000000;
But what if there are more digits after dot?
You have to truncate the second decimal position.
Double dou = 99.99;
double douOneDecimal = System.Math.Truncate (dou * 10) / 10;
string str = String.Format("{0:0.0}", douOneDecimal);
You can use the Floor method to round down:
string str = (Math.Floor(dou * 10.0) / 10.0).ToString("0.0");
The format 0.0 means that it will show the decimal even if it is zero, e.g. 99.09 is formatted as 99.0 rather than 99.
Update:
If you want to do this dynamically depending on the number of digits in the input, then you first have to decide how to determine how many digits there actually are in the input.
Double precision floating point numbers are not stored in decimal form, they are stored in binary form. That means that some numbers that you think have just a few digits actually have a lot. A number that you see as 1.1 might actually have the value 1.099999999999999945634.
If you choose to use the number of digits that is shown when you format it into a string, then you would simply format it into a string and remove the last digit:
// format number into a string, make sure it uses period as decimal separator
string str = dou.ToString(CultureInfo.InvariantCulture);
// find the decimal separator
int index = str.IndexOf('.');
// check if there is a fractional part
if (index != -1) {
// check if there is at least two fractional digits
if (index < str.Length - 2) {
// remove last digit
str = str.Substring(0, str.Length - 1);
} else {
// remove decimal separator and the fractional digit
str = str.Substring(0, index);
}
}

Creating fixed length numeric string

I have a certain number of files for which I need the filenames in my program. The files have a fixed naming fashion i.e. (prefix + digits).jpg. For e.g.: head001.jpg, head002.jpg, head003.jpg etc. etc.
The number of digits, in the end, can be varying - so the program has variables to change where the file naming starts from, where it ends and how many number digits are used in the naming. For e.g: A second scenario could be - tail00001.jpg, tail00002.jpg, tail00003.jpg etc. until tail00100.jpg
And in this case: start digit would be 0, end digit would be 100 and numDigits would be 5
In C++, I’ve seen this formatting being done as follows:
format <<prefix<<"%0"<<numDigits<<"d."<<filetype; //where format is a stringstream
However, I’m not quite sure about the best way to do this in C# and would like to know how to solve this.
Just use string.Format, with a precision specifier saying how many digits you want:
string name = string.Format("tail{0:d6}.jpg", index);
See the MSDN documentation for standard numeric string formats for more details.
You can build the string format up programmatically of course:
string name = string.Format("tail{0:d" + digits + "}.jpg", index);
Or use PadLeft as suggested by Vano. You might still want to use string.Format though:
string name = string.Format("tail{0}.jpg",
index.ToString().PadLeft(digits, '0'));
Using PadLeft has the advantage that it's easier to change the padding value, although I would imagine you'd always want it to be 0 anyway.
string has PadLeft method:
int n1 = 1;
string t1 = n1.ToString().PadLeft(5, '0'); // This will return 00001
int n10 = 10;
string t2 = n10.ToString().PadLeft(5, '0'); // This will return 00010 and so on...
You can do this using string.Format
var result = string.Format("{0}{1:00000}{2}", prefix, number, filetype)
Or you could use padleft
var result = prefix + number.ToString().PadLeft('0', numDigits) + "." + extension;
Or you can use a mix of the two :)
..and in this case: start digit would be 0, end digit would be 100 and
numDigits would be 5
You could use String.Format and the decimal format/precision specifier "D"` and a for-loop:
int start = 0;
int end = 100;
int numDigits = 5;
string name = "tail";
string extension = ".jpg";
for(int i = start; i <= end; i++)
{
string fileName = string.Format(
"{0}{1}{2}", name, i.ToString("D" + numDigits), extension);
Console.WriteLine(fileName);
}
Outputs:
tail00000.jpg
tail00001.jpg
tail00002.jpg
tail00003.jpg
tail00004.jpg
tail00005.jpg
tail00006.jpg
tail00007.jpg
tail00008.jpg
tail00009.jpg
tail00010.jpg
....
tail100.jpg
For modern .NET 5.0+ (2021 update)
int myint = 100;
string zeroPadded = $"{myint:d8}"; // "00000100"
string spacePadded = $"{myint,8}"; // " 100"

How to change 1 to 00001?

I want to have numbers with a fixed digit count.
example: 00001, 00198, 48484
I can do like this:
string value;
if (number < 10)
{
value = "0000" + number.ToString();
}
else if (number < 100)
{
value = "000" + number.ToString();
}
else if (number < 1000)
{
...
}
But this is a bit odd. Is there any built in function for my purpose?
Yes, there is:
string value = String.Format("{0:D5}", number);
According to the MS reference: http://msdn.microsoft.com/en-us/library/dd260048.aspx
You can pad an integer with leading zeros by using the "D" standard
numeric format string together with a precision specifier. You can pad
both integer and floating-point numbers with leading zeros by using a
custom numeric format string.
So:
To display the integer as a decimal value, call its ToString(String)
method, and pass the string "Dn" as the value of the format parameter,
where n represents the minimum length of the string.
Code:
string value = number.ToString("D5");
.NET fiddle: http://dotnetfiddle.net/0U9A6N
You should use the ToString() method with custom formating - see the docs. In particular the 0 specifier.
Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.
eg,
value = number.Tostring("00000");
string value = number.ToString("00000");
You can do it this way :
number.ToString("00000")
If you wish to return 5 digits numbers, you should use the PadLeft() function;
int Value = 101;
char pad = '0';
String sValue = Value.ToString();
sValue = sValue.s.PadLeft(5, char)
In this case, you don't have to test whether to add 1, 2 or 3 zeros, it'll automatically add the number of zeros needed to make it 5 digits number.
int input_number = Convert.ToInt32(txtinput.Text);
string number_value = input_number.ToString("00000");
I hope that it will solve your problem. It worked well for me in my previous project.
Test this code in your development. It should be worked properly without doubt.
Same as #Jojo's answer, but using C# 6's interpolated strings:
var value = $"{number:00000}";
Apart from String.Format, You can also use String.PadLeft
value = number.ToString().PadLeft(5, '0');

How to split a string based on every third character regardless of what the character is in c# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
.NET String.Format() to add commas in thousands place for a number
I am trying to add commas to a number for the presentation layer and need to cast and then split the number on every third character in order to join on a ','.
So if i have a string like this
546546555
desired output:
546,546,555
Other times, the number could be longer or shorter:
254654
desired output:
254,654
Is it possible to split in this manner then join with a comma?
tahnks!
EDIT:
Hi Everyone,
Thanks very much for your help.
To add to this post I also found a way to do this in SQL:
SUBSTRING(CONVERT(varchar, CAST(NumItems AS money), 1), 0, LEN(CONVERT(varchar, CAST(NumDocs AS money), 1)) - 2) as [NumDocs]
Rather than splitting the string manually, you should convert it to a number (or leave it as a number), and call the ToString method with the appropriate formatting:
Example
int value = 546546555;
string displayValue = value.ToString("#,#");
See this MSDN page for different format values:
C - Currency format
D - Decimal format
E - Scientific format
F - Fixed point format
G - General format
N - Number format
P - Percent format
R - Round trip format
X - Hexadecimal format
You should do this by converting your string to an integer, using Parse or ideally TryParse and use string formatting to display it:
var str = "546546555";
var formatted = String.Empty;
int value = 0;
if(int.TryParse(str,out value))
{
formatted = value.ToString("#,#");
}
Live example: http://rextester.com/FHO11833
Assuming you aren't only trying to output numbers, here's a quick function that I believe would do what you are after:
string splitter(string tosplit, int num, string splitstring)
{
string output = "";
for (int i = 0; i < tosplit.Length; i += num)
if (i + num < tosplit.Length)
output += tosplit.Substring(i, num) + ",";
else
output += tosplit.Substring(i);
return output;
}
Here, the output of splitter("546546555", 3, ",") would be 546,546,555
This would not be ideal for numbers though, as the other answers would cover this case perfectly.
Not very good code, but it works.
public static string GetString(string val, int number)
{
List<string> res = new List<string>();
res.Add("");
int counter = 0, i = 0;
while (i < val.Length)
{
while (res[counter].Length < number && i < val.Length)
{
res[counter] += val[i];
i++;
}
res.Add("");
counter++;
}
return string.Join(",", res.Where(r => !string.IsNullOrEmpty(r)));
}
val - your input string
number - number of characters you want to split, equals to 3 in your case
Gene S and Dan seem to have the answer IMHO. The nice thing about using the built in formatting is that you can write localizable code. For example, the "," is the numeric group separator in the US, but the "." is used in Spain.
var val = 12345678;
CultureInfo c = CultureInfo.CurrentCulture;
Application.CurrentCulture = new CultureInfo("EN-us");
var s = String.Format("{0:#,#}", val);
Application.CurrentCulture = new CultureInfo("ES-es");
var i = String.Format("{0:#,#}", val);
Application.CurrentCulture = c;

How to delete characters and append strings?

I am adding a new record to XML file, first I'm querying all existing items and storing the count in an int
int number = query.count()
and then increment the number by 1.
number = number + 1;
Now I want to format this value in a string having N00000000 format
and the number will occupy the last positions.
Pseudo code:
//declare the format string
sting format = "N00000000"
//calculate the length of number string
int length =number.ToString().Length();
// delete as many characters from right to left as the length of number string
???
// finally concatenate both strings with + operator
???
String output = "N" + String.Format ("00000000", length)
Alternatively if you change your formatstring to "'N'00000000" you can even use:
String output = String.Format (formatString, length)
Which means you can fully specify your output by changing your formatstring without having to change any code.
int i = 123;
string n = "N" + i.ToString().PadLeft(8, '0');
var result = number.ToString("N{0:0000000}");
HTH
You can use the built in ToString overload that takes a custom numeric format string:
string result = "N" + number.ToString("00000000");
Here is a another one ...
result = String.Format("N{0:00000000}",number);

Categories

Resources