C# String format patterns for truncating numbers to two decimal places (e.g. money) or none in the case of trailing zeros

Viewed 93

How do I convert the following examples numbers (decimal, double or float) to 2 decimal places truncating (rounding down) the digits to the right:

77.1455
52.00
714.1554
5552.0001

Should become like these

"77.14"
"52"
"714.15"
"5552"

Some suggested

String.Format("G29");
String.Format("0.00");

But they don't work as expected.

2 Answers

Use the "####.##" pattern to achieve the desired result with natural rounding (see bottom example for truncation). Few examples:

var f1 = 1000.3455f;
var result = f1.ToString("####.##");
//result = 1000.35

Round's down eliminating trailing zeros:

f1 = 1000.0001f;
result = f1.ToString("####.##");
//result = 1000;

Add a comma if to the formatting string for comma separated numbers >= 1000:

var f1 = 1000.3455f;
f1.ToString("#,###.##");
//result = 1,000.35;

And if you want to remove the trailing numbers beyond hundredths without natural rounding:

var f1 = 1000.3455f;
f1 = (float)Math.Round(f1, 2, MidpointRounding.ToZero);
result = f1.ToString("#,###.##");
//result = 1,000.34

You can truncate the value after two decimal places:

(Math.Truncate(100 * value) / 100).ToString();

Full sample:

static void Main(string[] args)
{
    float[] values = { 77.1455f, 52.00f, 714.1554f, 5552.0001f };
    string[] formattedValues = Format(values);
    Console.WriteLine(string.Join(Environment.NewLine, formattedValues));
}  

private static string[] Format(float[] values)
{
    return Array.ConvertAll(values, Convert);
}

private static string Convert(float value)
{
    return (Math.Truncate(100 * value) / 100).ToString();
}
Related