简体   繁体   中英

C# String.Format() to remove decimals after hundredths and remove decimals completely if decimals are trailing zeros

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.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM