hawbsl
hawbsl

Reputation: 16003

Is there a .Net FormatString for 1 to 2 decimal places?

I have a requirement to format a given number to at least 1 decimal place and up to 2 decimal places as in:

4      -> 4.0
4.1    -> 4.1
4.25   -> 4.25
4.3333 -> 4.33
4.5    -> 4.5
5      -> 5.0

Is there a FormatString string which will deliver this?

as in:

MyDecimal.ToString("[something here]")

Upvotes: 0

Views: 3233

Answers (5)

Roly
Roly

Reputation: 1536

Or to merge Anthony and Rahul's answers:

string.Format("{0:0.0#}", someNumber);

e.g.:

string formatStr = "{0:0.0#}";

var output = new StringBuilder();

var input = new List<double> { 4, 4.1, 4.25, 4.3333, 4.5, 5 };

foreach ( var num in input ) {
    output.AppendLine(num + " -> " + string.Format(formatStr, num));
}

/* output
4 -> 4.0
4.1 -> 4.1
4.25 -> 4.25
4.3333 -> 4.33
4.5 -> 4.5
5 -> 5.0
*/

Upvotes: 0

Rahul
Rahul

Reputation: 77866

Considering it in C#; it would be like below

//max. two decimal places
String.Format("{0:0.##}", 123.4567);      // "123.46"
String.Format("{0:0.##}", 123.4);         // "123.4"
String.Format("{0:0.##}", 123.0);         // "123"

Upvotes: 0

Alex K.
Alex K.

Reputation: 175766

The string "0.0#" should do that.

Upvotes: 1

Paul
Paul

Reputation: 36319

probably something like:

myDecimal.ToString("#.0#");

At least, based on the examples you gave hat'd work.

Upvotes: 1

Anthony Pegram
Anthony Pegram

Reputation: 126804

Yes, you can conditionally include a second decimal place with the # format placeholder.

MyDecimal.ToString("0.0#")

Upvotes: 5

Related Questions