string format in C#
I have value ranging from 1 to 10000000. After va开发者_JAVA百科lue 10000 i need to show values as 1E6,1E7,1E8,.... How to set this in string.Format ?
Thanks to all for replying.
Now i am able to display 1E5,1E6,1E7,....by using format "0.E0" but i dont want to set "E" from 1 to 10000. How to go about this ?You could use the exponent notation but I think that it will work for all numbers and not only those greater than 10000. You might need to have a condition to handle this case.
Something like this should do the trick:
void Main()
{
Console.WriteLine(NumberToString(9999));
Console.WriteLine(NumberToString(10000));
Console.WriteLine(NumberToString(99990));
Console.WriteLine(NumberToString(100000));
Console.WriteLine(NumberToString(10000000));
}
// Define other methods and classes here
static string NumberToString(int n)
{
return (n > 10000) ? n.ToString("E") : n.ToString();
}
=>
9999
10000
9.999000E+004
1.000000E+005
1.000000E+007
nb: pick a better name for the function.
Scientific notation? Here's some help on that: http://msdn.microsoft.com/en-us/library/0c899ak8.aspx#SpecifierExponent
I suggest to refer to the value as a float. That way you can use the "NumberStyles.AllowExponent" and that will provide exactly what you are looking for.
string i = "100000000000";
float g = float.Parse(i,System.Globalization.NumberStyles.AllowExponent);
Console.WriteLine(g.ToString());
String.Format("10^8 = {0:e}", 100000000"); //The "e" will appear lowercase String.Format("10^8 = {0:E}", 100000000"); //The "E" will appear in uppercase
If you want it to be prettier, try this:
Console.WriteLine("10^8 = " + 100000000.ToString("0.##E0"));
精彩评论