简体   繁体   中英

Decimal Formatting in C#

I want a function that shows at most N decimal places, but does not pad 0's if it is unnecessary, so if N = 2,

2.03456 => 2.03
2.03 => 2.03
2.1 => 2.1
2 => 2

Every string formatting thing I have seen will pad values like 2 to 2.00, which I don't want

How about this :

// 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"

尝试这个:

string s = String.Format("{0:0.##}", value);

I made a quick extension method:

public static string ToString(this double value, int precision)
{
    string precisionFormat = "".PadRight(precision, '#');
    return String.Format("{0:0." + precisionFormat + "}", value);
}

Use and output:

double d = 123.4567;
Console.WriteLine(d.ToString(0));  // 123
Console.WriteLine(d.ToString(1));  // 123.5
Console.WriteLine(d.ToString(2));  // 123.46
Console.WriteLine(d.ToString(3));  // 123.457
Console.WriteLine(d.ToString(4));  // 123.4567

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