Duncan Palmer
Duncan Palmer

Reputation: 2913

Round to a certain decimal place

I am calculating the average of some values. Everything works fine. What I want to do is to round the double to the 2nd decimal place.

e.g.

I would have 0.833333333333333333 displayed as 0.83

Is there anyway to do this?

Upvotes: 0

Views: 490

Answers (6)

middelpat
middelpat

Reputation: 2585

Round the double itself like:

Math.Round(0.83333, 2, MidpointRounding.AwayFromZero);

(You should define MidpointRounding.AwayAwayFromZero to get the correct results. Default this function uses bankers rounding. read more about bankers rounding: http://www.xbeat.net/vbspeed/i_BankersRounding.htm so you can see why this won't give you the right results)

Or just the display value for two decimals:

myDouble.ToString("F");

Or for any decimals determined by the number of #

myDouble.ToString("#.##")

Upvotes: 9

Milind Thakkar
Milind Thakkar

Reputation: 980

Use

Math.Round(decimal d,int decimals);

as

Math.Round(0.833333333,2); 

This will give you the result 0.83.

Upvotes: 1

Tigran
Tigran

Reputation: 62248

If you want to see 0.85781.. as 0.85, the easiest way is to multiply by 100, cast to int and divide by 100.

int val = (int)(0.833333333333333333 * 100); 
var result = val /100;

It should produce the result you're looking for.

Upvotes: -1

sajanyamaha
sajanyamaha

Reputation: 3198

Try

decimalVar = 0.833333333333333333;
decimalVar.ToString ("#.##");

Upvotes: 0

Mike de Klerk
Mike de Klerk

Reputation: 12328

double d = 0.833333333333333333;
Math.Round(d, 2).ToString();

Upvotes: 0

Andras Zoltan
Andras Zoltan

Reputation: 42333

You say displays as - so that would be:

var d = value.ToString("f2");

See Standard numeric format strings

If you actually want to adjust the value down to 2dp then you can do what @middelpat has suggested.

Upvotes: 1

Related Questions