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.user447356– user4473562013-10-06 10:47:44 +00:00Commented 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 Hopkinson– Tony Hopkinson2013-10-06 10:58:47 +00:00Commented Oct 6, 2013 at 10:58
Add a comment
|
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
3 Comments
apc
Like ubsch I have the requirement to do this without using substring and unfortunatly I don't think it is possible.
Soner Gönül
@apc Why do you think that not possible? I added an example without
Substring.apc
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.
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)