Is there a less recursive way to format numbers?

Is there a C # equivalent for C ++ streaming manipulators? For instance,

int decimalPlaces = 2; double pi = 3.14159; cout.precision(decimalPlaces); cout << pi; 

It seems strange to me to format a number before a string in order to format a number into a string. For instance,

 int decimalPlaces = 2; double pi = 3.14159; string format = "N" + decimalPlaces.ToString(); pi.ToString(format); 

Is this what was done in C #, or am I missing something?

+4
source share
1 answer

I would squeeze it a little:

 int decimalPlaces = 2; double pi = 3.14159; pi.ToString("N" + decimalPlaces); 

In addition, you do not need to format the number before printing it. Print media will also accept formatting constructors.

+2
source

All Articles