Home > database >  C# String.Format() to remove decimals after hundredths and remove decimals completely if decimals ar
C# String.Format() to remove decimals after hundredths and remove decimals completely if decimals ar

Time:09-13

These floats

77.1455
52.00
714.1554
5552.0001

Should become like these

77.14
52
714.15
5552

Some suggested

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

But they don't work as I need.

CodePudding user response:

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

CodePudding user response:

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();
}
  •  Tags:  
  • c#
  • Related