format for double type

  • Thread starter Thread starter Carlos
  • Start date Start date
C

Carlos

Hi all,

just wanted to know how can I just quickly round to nearest
100th, and use the first two decimal places of a double value in a textbox,
instead of all the decimals.

Thanks in advance,

Carlos
 
When it comes to rounding, take a look at Math.Round(). In order to round a
var to the 100th’s place, you’d simply do something like:

double pi = 3.14159265;
pi = Math.Round(pi, 2);

In this example, pi ends up with the value 3.14 because of the second
argument passed into Round() specifies the # of decimal places you want to
round to. After this, you simply output the variable to where you see fit.

Brendan
 
Hi,
just wanted to know how can I just quickly round to nearest
100th, and use the first two decimal places of a double value in a
textbox, instead of all the decimals.

Brendan showed you how to round, if you need to. However, if all you are
doing is populating a text box, you will be converting the double to a
string anyway. You could just let the framework do it while formatting the
double as string.

double d = 12.3456789;
Console.WriteLine(d.ToString("N"));

This produces the following output:

12.35

As you can see, the number was correctly rounded during formatting and if
you are not doing anything else with it, then prior rounding in your code
isn't necesary. If you don't want thousands separated, you can use the
custom format string "0.00" instead of standard "N".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top