Reputation: 16003
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
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
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
Reputation: 36319
probably something like:
myDecimal.ToString("#.0#");
At least, based on the examples you gave hat'd work.
Upvotes: 1
Reputation: 126804
Yes, you can conditionally include a second decimal place with the #
format placeholder.
MyDecimal.ToString("0.0#")
Upvotes: 5