Re: Formating numbers
- From: Göran Andersson <guffa@xxxxxxxxx>
- Date: Sun, 15 Jun 2008 15:04:55 +0200
Paul Hirose wrote:
"Steven Cheng [MSFT]" <stcheng@xxxxxxxxxxxxxxxxxxxx> wrote in message
news:FthwzudyIHA.3644@xxxxxxxxxxxxxxxxxxxxxxxxx
BTW, you can also use string.Format function to format multiple
output
objects.e.g.
double dv = 343.4343;
Console.WriteLine(string.Format("{0:f3}", dv));
Is there a way to control the precision at run time? Sometimes the
appropriate precision isn't known at compile time.
In C you can print double d with 3 decimal places like this:
printf("%.3f\n", d);
And if the precision needs to be set at run time, you get i decimal
places like this:
printf("%.*f\n", i, d);
I couldn't figure out how to do that in C#, so I had to construct the
control string with a StringBuilder. It worked, but the old fashioned
printf() would have been a lot cleaner.
The .NET formatting doesn't support formatting in the formatting, as the printf function does. Using string operations to construct a format string is the way to do it.
If you are formatting just a single value, you can use a ToString overload instead of the string.Format method:
double dv = 343.4343;
int decimals = 3;
string format = "f" + decimals.ToString();
Console.WriteLine(dv.ToString(format));
--
Göran Andersson
_____
http://www.guffa.com
.
- References:
- RE: Formating numbers
- From: Steven Cheng [MSFT]
- Re: Formating numbers
- From: Paul Hirose
- RE: Formating numbers
- Prev by Date: Clipboard Application - Pasting to IE
- Next by Date: Windows Update Agent API and other OSes
- Previous by thread: Re: Formating numbers
- Next by thread: Re: Sound issue with watching TV thru XP Media Center version 2002
- Index(es):
Relevant Pages
|