Add zero padding to string using $"{x:Dn}" notation - c#

I am a big fan of the new $"" notation to format strings in c#. Hence I would like to use this notation to pre-pend some leading zero's to an integer.
var i = 10;
var s = $"{i:D4}";
This does the job well en results in 0010.
But what if the amount of zero's or the total length is variable. How do I accomplish that using this new notation ?
I'm looking for somthing like :
var TotalLength = 4; // IRL it would be a calculated value.
var format = "D" + TotalLength.ToString();
var i = 10;
var s = $"{i:format}";
variant I've tried but does not work either.
$"{i:{format}}"
Any suggestions ?

Or - mixing your something like and Rob's method:
var TotalLength = 4; // IRL it would be a calculated value.
var format = TotalLength.ToString("'D'0");
var i = 10;
var s = $"{i.ToString(format)}";

Based on the suggestions given I've made two extension methods :
public static String GetDnFormat(this int i)
{
return ((int)Math.Log10(i) + 1).ToString("'D'0");
}
public static String ToDnFormat(this int i, int source)
{
var format = source.GetDnFormat();
return i.ToString(format);
}
Usage :
var Page = 10;
var PageCount = 124;
var PageLabel = $"{Page.ToDnFormat(PageCount)}/{PageCount}"; // result : 010/124

Related

how to show number of digits on users's request?

for example: if a string value is "123456.7890" .
if user enters the length 6 and the other value 2 for the decimal place.
the output value should be like "123456.78"
if user enters the length 5 and the other value 3 for the decimal place.
the output value should be like "12345.789"
string s = "123456.7890";
string a = string.Format("{0, 2:F2}", s);
int index = a.IndexOf('.');
a = a.Substring(index, (a.Length-index));
One approach could be like this:
NOTE: If the string's length is less than the number of characters you're taking, code will throw an exception ArgumentOutOfRangeException
int LeftPlaces = 4;
int RightPlaces = 2;
String Input = "123456.7890";
String[] Splitted = Input.Split('.');
String StrLeft = Splitted[0].Substring(0, LeftPlaces);
String StrRight = Splitted[1].Substring(0, RightPlaces);
Console.WriteLine(StrLeft + "." + StrRight);
Output: 1234.78
The most crude and direct way would be:
var length = 5;
var decimalPlaces = 2;
var s = "123456.7890";
var data = s.Split('.');
var output1 = data[0].Substring(0, length);
var output2 = data[1].Substring(0, decimalPlaces);
var result = output1 + "." + output2;
If you want to do this without strings, you can do so.
public decimal TrimmedValue(decimal value,int iLength,int dLength)
{
var powers = Enumerable.Range(0,10).Select(x=> (decimal)(Math.Pow(10,x))).ToArray();
int iPart = (int)value;
decimal dPart = value - iPart;
var dActualLength = BitConverter.GetBytes(decimal.GetBits(value)[3])[2];
var iActualLength = (int)Math.Floor(Math.Log10(iPart) + 1);
if(dLength > dActualLength || iLength > iActualLength)
throw new ArgumentOutOfRangeException();
dPart = Math.Truncate(dPart*powers[dLength]);
iPart = (int)(iPart/powers[iActualLength - iLength]);
return iPart + (dPart/powers[dLength]);
}
Client Call
Console.WriteLine($"Number:123456.7890,iLength=5,dLength=3,Value = {TrimmedValue(123456.7890m,5,3)}");
Console.WriteLine($"Number:123456.7890,iLength=6,dLength=2,Value = {TrimmedValue(123456.7890m,6,2)}");
Console.WriteLine($"Number:123456.7890,iLength=2,dLength=4,Value = {TrimmedValue(123456.7890m,2,4)}");
Console.WriteLine($"Number:123456.7890,iLength=7,dLength=3,Value = {TrimmedValue(123456.7890m,7,3)}");
Output
Number:123456.7890,iLength=5,dLength=3,Value = 12345.789
Number:123456.7890,iLength=6,dLength=2,Value = 123456.78
Number:123456.7890,iLength=2,dLength=4,Value = 12.789
Last call would raise "ArgumentOutOfRangeException" Exception as the length is more than the actual value

Convert int to string in specific format

I have a int which I want to convert to string in specific format.
For example,
-1 to -01:00
It is easy if I have positive number (i.e 1 to 01:00). I can use following code:
var time = 6;
var convertTime = "0" + time + ":00";
Output:
06:00
I am not sure how to achieve same with negative number.
var time = -6;
var convertTime = /* what to do here */ + time + ":00";
Desired Output:
-06:00
Just use string.Format for that
int time = -6;
var convertTime = string.Format("{0:00}:00", time);
Or if you have C# 6 you can do an interpolated string.
var convertTime = $"{time:00}:00";
var time = -6;
var convertTime = (time < 0 ? "-" : String.Empty) + Math.Abs(time).ToString("D2") + ":00";
var time = (myInt*100).ToString("00:00");
Or if using C# 6 (VS2015):
var input = -6;
var time = $"{input:00}:00";
Here's an example utilizing TimeSpan.
public void TestTimeSpan()
{
var ts = new TimeSpan(-1, 0, 0);
var s = string.Format("{0}{1:hh\\:mm}", ts < TimeSpan.Zero? "-": string.Empty, ts);
Assert.AreEqual("-1:00", s);
}

get only integer value from string

I need to get only the last number from the string. The string contains pattern of string+integer+string+integer i.e. "GS190PA47". I need to get only 47 from the string.
Thank you
A simple regular expression chained to the end of the string for any number of integer digits
string test = "GS190PA47";
Regex r = new Regex(#"\d+$");
var m = r.Match(test);
if(m.Success == false)
Console.WriteLine("Ending digits not found");
else
Console.WriteLine(m.ToString());
string input = "GS190PA47";
var x = Int32.Parse(Regex.Matches(input, #"\d+").Cast<Match>().Last().Value);
If string always ends with number, you can simply use \d+$ pattern, as Steve suggests.
you can try this regex:
(\d+)(?!.*\d)
you can test it with this online tool: link
Try this:
string input = "GS190PA47";
Regex r = new Regex(#"\d+\D+(\d+)");
int number = int.Parse(r.Match(input).Groups[1].Value);
Pattern means we find set of digits (190), next set of non-digit chars (PA) and finally sought-for number.
Don't forget include using System.Text.RegularExpressions directive.
Not sure if this is less or more efficient than RegEx (Profile it)
string input = "GS190PA47";
var x = Int32.Parse(new string(input.Where(Char.IsDigit).ToArray()));
Edit:
Amazingly it is actually much faster than regex
var a = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
{
string input = "GS190PA47";
var x = Int32.Parse(new string(input.Reverse().TakeWhile(Char.IsDigit).Reverse().ToArray()));
}
a.Stop();
var b = a.ElapsedMilliseconds;
Console.WriteLine(b);
a = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
{
string input = "GS190PA47";
var x = Int32.Parse(Regex.Matches(input, #"\d+").Cast<Match>().Last().Value);
}
a.Stop();
b = a.ElapsedMilliseconds;
Console.WriteLine(b);

Adding numbers to a string?

I have strings that look like "01", "02". Is there an easy way that I can change the string into a number, add 1 and then change it back to a string so that these strings now look like "02", "03" etc. I'm not really good at C# as I just started and I have not had to get values before.
To get from a string to an integer, you can youse int.Parse():
int i = int.Parse("07");
To get back into a string with a specific format you can use string.Format():
strings = string.Format("{0:00}",7);
The latter should give "07" if I understand http://www.csharp-examples.net/string-format-int/ correctly.
You can convert the string into a number using Convert.ToInt32(), add 1, and use ToString() to convert it back.
int number = Convert.ToInt32(originalString);
number += 1;
string newString = number.ToString();
Parse the integer
int i = int.Parse("07");
add to your integer
i = i + 1;
make a new string variable and assign it to the string value of that integer
string newstring = i.ToString();
AddStringAndInt(string strNumber, int intNumber)
{
//TODO: Add error handling here
return string.Format("{0:00}", (int.TryParse(strNumber) + intNumber));
}
static string StringsADD(string s1, string s2)
{
int l1 = s1.Count();
int l2 = s2.Count();
int[] l3 = { l1, l2 };
int minlength = l3.Min();
int maxlength = l3.Max();
int komsu = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < maxlength; i++)
{
Int32 e1 = Convert.ToInt32(s1.PadLeft(maxlength, '0').ElementAt(maxlength - 1 - i).ToString());
Int32 e2 = Convert.ToInt32(s2.PadLeft(maxlength, '0').ElementAt(maxlength - 1 - i).ToString());
Int32 sum = e1 + e2 + komsu;
if (sum >= 10)
{
sb.Append(sum - 10);
komsu = 1;
}
else
{
sb.Append(sum);
komsu = 0;
}
if (i == maxlength - 1 && komsu == 1)
{
sb.Append("1");
}
}
return new string(sb.ToString().Reverse().ToArray());
}
I needed to add huge numbers that are 1000 digit. The biggest number type in C# is double and it can only contain up to 39 digits. Here a code sample for adding very huge numbers treating them as strings.

Need code for addition of 2 numbers

I am having the numbers follows taken as strings
My actual number is 1234567890123456789
from this i have to separate it as s=12 s1=6789 s3=3456789012345
remaining as i said
I would like to add as follows
11+3, 2+4, 6+5, 7+6, 8+7, 9+8 such that the output should be as follows
4613579012345
Any help please
public static string CombineNumbers(string number1, string number2)
{
int length = number1.Length > number2.Length ? number1.Length : number2.Length;
string returnValue = string.Empty;
for (int i = 0; i < length; i++)
{
int n1 = i >= number1.Length ? 0 : int.Parse(number1.Substring(i,1));
int n2 = i >= number2.Length ? 0 : int.Parse(number2.Substring(i,1));
int sum = n1 + n2;
returnValue += sum < 10 ? sum : sum - 10;
}
return returnValue;
}
This sounds an awful lot like a homework problem, so I'm not giving code. Just think about what you need to do. You are saying that you need to take the first character off the front of two strings, parse them to ints, and add them together. Finally, take the result of the addition and append them to the end of a new string. If you write code that follows that path, it should work out fine.
EDIT: As Ralph pointed out, you'll also need to check for overflows. I didn't notice that when I started typing. Although, that shouldn't be too hard, since you're starting with a two one digit numbers. If the number is greater than 9, then you can just subtract 10 to bring it down to the proper one digit number.
How about this LINQish solution:
private string SumIt(string first, string second)
{
IEnumerable<char> left = first;
IEnumerable<char> right = second;
var sb = new StringBuilder();
var query = left.Zip(right, (l, r) => new { Left = l, Right = r })
.Select(chars => new { Left = int.Parse(chars.Left.ToString()),
Right = int.Parse(chars.Right.ToString()) })
.Select(numbers => (numbers.Left + numbers.Right) % 10);
foreach (var number in query)
{
sb.Append(number);
}
return sb.ToString();
}
Tried something:
public static string NumAdd(int iOne, int iTwo)
{
char[] strOne = iOne.ToString().ToCharArray();
char[] strTwo = iTwo.ToString().ToCharArray();
string strReturn = string.Empty;
for (int i = 0; i < strOne.Length; i++)
{
int iFirst = 0;
if (int.TryParse(strOne[i].ToString(), out iFirst))
{
int iSecond = 0;
if (int.TryParse(strTwo[i].ToString(), out iSecond))
{
strReturn += ((int)(iFirst + iSecond)).ToString();
}
}
// last one, add the remaining string
if (i + 1 == strOne.Length)
{
strReturn += iTwo.ToString().Substring(i+1);
break;
}
}
return strReturn;
}
You should call it like this:
string strBla = NumAdd(12345, 123456789);
This function works only if the first number is smaller than the second one. But this will help you to know how it is about.
In other words, you want to add two numbers treating the lesser number like it had zeroes to its right until it had the same amount of digits as the greater number.
Sounds like the problem at this point is simply a matter of finding out how much you need to multiply the smaller number by in order to reach the number of digits of the larger number.

Categories