Spike
Spike

Reputation: 2027

Is there a less recursive feeling way of formatting numbers?

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

Answers (1)

Marcelo Cantos
Marcelo Cantos

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

Related Questions