Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string format in C#

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 ?

like image 941
Guddu Avatar asked Aug 16 '10 08:08

Guddu


People also ask

What is a string format?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments.

What is %d %f %s in C?

The first argument to printf is a string of identifiers. %s refers to a string %d refers to an integer %c refers to a character. Therefore: %s%d%s%c\n prints the string "The first character in sting ", %d prints i, %s prints " is ", and %c prints str[0]. Follow this answer to receive notifications.

What is %d and & in C?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.


2 Answers

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.

like image 64
Darin Dimitrov Avatar answered Nov 14 '22 04:11

Darin Dimitrov


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.

like image 26
ngoozeff Avatar answered Nov 14 '22 03:11

ngoozeff