I know this should be an easy thing but I don't know how to do it.
I want to insert some data into a table, and I'm using loops because I have over 1million datas to insert. It should look like this "PM-0000000000, PM-0000000001......... PM-0000099999". Now here's the problem. I don't know how to add those zeros in front according to the numbers that are after the zeros. the number length (PM-"0000000000") Should always be 10.
Help please ?
Use padleft to fill the string with the number of zeros you need
string value="99999";
string concat= "PM" + value.PadLeft(10, '0');
Please check this documentation: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#DFormatString
int yourNumber = 999;
string filledNumber = yourNumber.ToString("D10");
Where D10 means, your number will be filled to 10 digits.
You can do string result = number.ToString("0000000000");
But I prefer #Kasyx's answer above. (I added this answer for completeness.)
you can generate full code using string.Format
string.Format("PM-{0:D10}", intval)
Related
I am making a simple learning game where a number is generated and the user will have to enter the word. The problem is Im trying to get a hint button working basically when the user clicks the hint button a message box will display the first character of the string which is in the array.
Here is a example of what my array looks like.
static string[] numberList = { "one","two", "Three","four","five","Six","Seven","Eight","Nine","Ten"};
So if the number is 2 and the strings are always in that order, then you can do
var firstletter = numberList[2-1][0];
That will get you a Char. If you want that also as string then do
firstletter.ToString();
just like this
var first = numberList[2-1][0];
first.ToString();
I don't know if this is optimized, but I like using substring() because it's very obvious what I want.
numberlist[i-1].Substring(0, 1);
where 'i' is the number you are looking for (subtract 1 because arrays use a 0-based index)
I have an string which is always 12 digits long
Its starts with 'PSS1'
'PSS100000300'
So I need to extract '300'
I can't just grab the last 3 digits as the number can increase to say
'PSS100010300'
And would need the value extracted to be '10300'
If I understood correctly, you want to skip first 4 characters and then zeross till the first non-zero characters. Try this one:
s = new string(s.Substring(4).SkipWhile(x => x == '0').ToArray());
Or, as #Blorgbeard suggested,
s = int.Parse(s.Substring(4)).ToString();
There is a slight difference between the methods. If you pass "PSS100000000", the first one returns an empty string, the second one returns "0". Not sure which result is expected.
Try this :
s = Convert.ToInt32(s.Replace("PSS1", string.Empty)).ToString()
The only problem with using int.Parse is that if you happen to ever come across this situation and the value you are after is not a number - let's say it might have a character in it...the int.Parse will throw an Exception.
That is why I would do it like this:
string fullPSS1String = "PSS10000#001";
string afterPSS1 = fullPSS1String.Substring(4).TrimStart('0');
I am not being picky, just trying to think of all situations. I know that the first option would not throw an Exception...but I feel that doing it this way is more direct.
How do I get the output of this to read 0 instead of 00 when the value is 0?
String.Format("{0:0,0}", myDouble);
string.Format("{0:#,0}", myDouble);
(tested version)
String.Format("{0:#,0}", myDouble);
Another alternative is to use this:
string s = string.Format("{0:n0}", myDouble);
If you always want commas as the thousands separator and not to use the user's locale then use this instead:
string s = myDouble.ToString("n0", CultureInfo.InvariantCulture);
While the posted answers here ("{0:#,0}") are correct I would strongly suggest using a more readable picture (also to avoid confusion about decimal/thousand separators):
string.Format("{0:#,##0}", v); // to print 1,234
string.Format("{0:#,##0.00}", v); // to print 1,234.56
But all those pictures work the same, including 2 comma's for 1e6 etc.
How do I in .NET format a number as percentage without showing the percentage sign?
If I have the number 0.13 and use the format string {0:P0} the output is 13 %.
However I would like to get 13 instead, without having to multiply the number by 100 and using the format string {0:N0}.
(Background: In ASP.NET I have a GridView with a BoundField where I would like to display a number as percentage but without the percentage sign (%). How do I do that?)
Thanks for the answers. At the time of editing 4 out of 6 suggest what I would like to avoid, as explained above. I was looking for a way to use a format string only, and avoid multiplying by 100 and using {0:N0}, but the answers indicate that's impossible...
Solved by using the accepted solution by Richard:
public class MyCulture : CultureInfo
{
public MyCulture()
: base(Thread.CurrentThread.CurrentCulture.Name)
{
this.NumberFormat.PercentSymbol = "";
}
}
Thread.CurrentThread.CurrentCulture = new MyCulture();
Define a custom culture with its own NumberFormatInfo which returns String.Empty for its PercentSymbol property.
Then use that custom culture for impacted pages (or for the whole application). This could be done by cloning from the default so other regional settings are preserved.
Why don't you just multiply the number by 100 and use your "{0:N0}" format string? That seems to me to be the easiest solution.
Unless you can come up with a viable reason why that's out of the question, that's my advice. It's not rocket science :-)
but multiplying by 100 is exactly what you want!
protected void myGrdiView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
myObjectType ot = (myObjectType)e.Row.DataItem;
ot.myNumber = ot.myNumber * 100; // multiply by 100
}
}
and in the HTML
<asp:BoundField DataType="myNumber" HeaderText="%" StringFormat="{0:N0}" />
The MSDN* has this under "Custom Numeric Format Strings":
The presence of a '%' character in a
format string causes a number to be
multiplied by 100 before it is
formatted. The appropriate symbol is
inserted in the number itself at the
location where the '%' appears in the
format string. The percent character
used is dependent on the current
NumberFormatInfo class.
But the example shows that it also outputs the % sign - not what you want, but perhaps settable to nothing via the NumberFormatInfo class?
However, I agree with Pax and can't see why do don't go with the * 100 and {0:N0}
**Accessing from within Visual Studio so no link*
How about this...
String.Format("{0:P0}",0.13).Replace("%","")
EDIT: This should work across cultures:
var percentSymbol = CultureInfo.CurrentCulture.NumberFormat.PercentSymbol;
String.Format("{0:P0}",0.13).Replace(percentSymbol,"")
There is also this solution which may be more elegant but slightly more code.
How about a trim?
double d = .102;
string percent = d.ToString("P0").Trim(' ', '%');
A points to consider first, a percentage displayed without a % is a number so lets ignore the percentage aspect. You want to know how to display a number that's 1 or less as 100 or less. I appreciate that it's bound so you can't modify it at display time so why not modify it at query time, i.e. SELECT (value*100) AS Percentage, ...?
You could also try something like
string newString = "0.13".Replace("0.", string.Empty) + "%";
Here is an example using NumberFormatInfo as #Richard suggested:
string.Format(new NumberFormatInfo { PercentSymbol = string.Empty }, "{0:0%}", 0.123); // => 12
Here is another shorter and cleaner way to do it.
$"{rate * 100:F2}"
The problem is with the convert of the txt box value, but why?
string strChar = strTest.Substring(0, Convert.ToInt16(txtBoxValue.Text));
Error is: Input string was not in a correct format.
Thanks all.
txtBoxValue.Text probably does not contain a valid int16.
A good way to avoid that error is to use .tryParse (.net 2.0 and up)
int subLength;
if(!int.TryParse(txtBoxValue.Text,out subLength)
subLength= 0;
string strChar = strTest.Substring(0, subLength);
This way, if txtBoxValue.Textdoes not contain a valid number then subLength will be set to 0;
One thing you may want to try is using TryParse
Int16 myInt16;
if(Int16.TryParse(myString, out myInt16)
{
string strChar = strTest.Substring(0, myInt16);
}
else
{
MessageBox.Show("Hey this isn't an Int16!");
}
A couple reasons the code could be faulty.
To really nail it down, put your short conversion on a new line, like this:
short val = Convert.ToInt16(txtBoxValue.Text);
string strChar = strTest.Substring(0, val);
Likely the value in txtBoxValue.Text is not a short (it might be too big, or have alpha characters in it). If it is valid and val gets assigned, then strTest might not have enough characters in it for substring to work, although this normally returns a different error. Also, the second parameter of substring might require an int (not sure, can't test right now) so you may need to actually convert to int32 instead of 16.
What is the value of txtBoxValue.Text during your tests?
ASP.NET offers several validation controls for checking user input. You should use something like a CompareValidator or RegularExpressionValiditor in your WebForm if you're expecting a specific type of input, eg, an Integer.