Reputation: 2027
Is there a C# equivalent of C++'s stream manipulators? Eg
int decimalPlaces = 2;
double pi = 3.14159;
cout.precision(decimalPlaces);
cout << pi;
It feels weird having to format a number to a string in order to format a number to a string. Eg
int decimalPlaces = 2;
double pi = 3.14159;
string format = "N" + decimalPlaces.ToString();
pi.ToString(format);
It that just how it's done in C#, or did I miss something?
Upvotes: 4
Views: 108
Reputation: 185842
I would shrink it slightly:
int decimalPlaces = 2;
double pi = 3.14159;
pi.ToString("N" + decimalPlaces);
Also, you don't have to format the number before printing it. The printing facilities will accept formatting constructs too.
Upvotes: 2