Re: Formating numbers

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



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
.



Relevant Pages

  • GridView formatting rows/columns question
    ... I've been looking into different ways of formatting columns/rows in the ... GridView control. ... to a string. ...
    (microsoft.public.dotnet.framework.aspnet)
  • Re: Formatting Text "Within" a Control
    ... consider using a Rich Text ActiveX control. ... I was able to simulate formatting parts of text within a ... > Dim strFirst As String 'Unformatted text in string ...
    (microsoft.public.access.reports)
  • Re: Inserting a date
    ... If the Payment_Date is a DateTime variable, then you really need to control ... the formatting, otherwise your first german temp who sets her regional ...
    (microsoft.public.access.modulesdaovba)
  • Re: double with precision
    ... I would like to save my double variable with a precision of 2 decimal ... if the reason you want to round the value ... use a java.text.NumberFormat object to control the way ... its value is converted to a string. ...
    (comp.lang.java.help)
  • Re: Why (0.09+0.01-0.1) is not equal to 0.09+0.01-0.1 ?
    ... > gives full accuracy by default, but also includes rounding algorithms ... > partitioned mantissa by without risk of overflow ... > Function D2BAs String ... the work involved in avoiding lost precision due to type ...
    (microsoft.public.excel)