Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
956 views
in Technique[技术] by (71.8m points)

string - How do I format a Decimal to a programatically controlled number of decimals in c#?

How can I format a number to a fixed number of decimal places (keep trailing zeroes) where the number of places is specified by a variable?

e.g.

int x = 3;
Console.WriteLine(Math.Round(1.2345M, x)); // 1.234 (good)
Console.WriteLine(Math.Round(1M, x));      // 1   (would like 1.000)
Console.WriteLine(Math.Round(1.2M, x));    // 1.2 (would like 1.200)

Note that since I want to control the number of places programatically, this string.Format won't work (surely I ought not generate the format string):

Console.WriteLine(
    string.Format("{0:0.000}", 1.2M));    // 1.200 (good)

Should I just include Microsoft.VisualBasic and use FormatNumber?

I'm hopefully missing something obvious here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try

decimal x = 32.0040M;
string value = x.ToString("N" + 3 /* decimal places */); // 32.004
string value = x.ToString("N" + 2 /* decimal places */); // 32.00
// etc.

Hope this works for you. See

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

for more information. If you find the appending a little hacky try:

public static string ToRoundedString(this decimal d, int decimalPlaces) {
    return d.ToString("N" + decimalPlaces);
}

Then you can just call

decimal x = 32.0123M;
string value = x.ToRoundedString(3);  // 32.012;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...