I have a number like 6348725, displayed as String, but I want to display only the last 6 digits (348725) with String.Format. Is there a way to do this? I know, there is the Substring Function (or Int calculation with % (Mod in VB)), but I want to use a FormatString by a User Input from a TextBox.
-
9Is this homework? Can't see any reason for such a weird requirement.– Shadow WizardCommented Oct 6, 2013 at 10:47
-
When you put a width in the format specifier, it's to pad the value. Can't think of a single reason why I would want to implicitly and silently drop information when displaying. Such a need would indicate to me there was something horribly wrong earlier on in the implementation.– Tony HopkinsonCommented Oct 6, 2013 at 10:58
3 Answers
I don't understand why you need String.Format
but you can use it like;
string s = "6348725";
TextBox1.Text = s.Substring(s.Length - 6)); // Textbox will be 348725
Okey, I just wanna show a dirty way without Substring
;
string s = "6348725";
var array = new List<char>();
if (s.Length > 6)
{
for (int i = s.Length - 6; i < s.Length; i++)
{
array.Add(s[i]);
}
}
Console.WriteLine(string.Join("", array)); // 348725
-
1Like ubsch I have the requirement to do this without using substring and unfortunatly I don't think it is possible.– apcCommented Mar 17, 2015 at 14:50
-
@apc Why do you think that not possible? I added an example without
Substring
. Commented Mar 17, 2015 at 15:11 -
It dosn't solve the problem using String.Format alone, which isn't possible and so there is no answer. An example of where this might be used is in an application in which the user can configure the format of some displayed data. In my case a specifc customer had the need was to display the first 3 number in the year (e.g. 201) followed by another value {0,3:yyyy}{1} would seem like it might work but dosn't as the 3 only pads and dosn't substring/trim.– apcCommented Mar 17, 2015 at 16:13
Generally you can do this as Soner Gönül said.
string s = "6348725";
TextBox1.Text = string.Format("Your number: {0}", s.Substring(s.Length-6)
If you need the full funcionality of String.Format and can replace your String.Format method take a look at SmartFormat.NET: https://github.com/scottrippey/SmartFormat.NET
It claims to be compatible with String.Format parameters and while it dosn't have the functionality you require yet it could easily be modified to trim as well as pad. (See Extensions/DefaultFormatter.cs line 63 to 84)