views:

96

answers:

5

I have value ranging from 1 to 10000000. After value 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 ?

+2  A: 

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.

Darin Dimitrov
A: 

Scientific notation? Here's some help on that: http://msdn.microsoft.com/en-us/library/0c899ak8.aspx#SpecifierExponent

Rob
A: 

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());
Adibe7
thanks but i need to show only 1E11 but your code shows + symbol which i dont need
Girish1984
This is the opposite. Here you parse a float from a string. When it is a float it doesn't have any formatting, of course, and printing it just prints the number.
Kobi
A: 
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"));
AndreyKo
+2  A: 

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.

ngoozeff
Probably be even nicer as an extension method...
Dan Diplo
@Dan: its tagged C#2.0, did that version have extension methods? I thought they were introduced in 3.0. But yes, it would be much nicer as an extension method.
ngoozeff