ozkank
ozkank

Reputation: 1462

Converting Decimal To Integer

string retval;

retval = Decimal.ToInt32(1899.99M).ToString();

the output is 1899. But i want to if decimal is bigger .5 then output is 1900 else then ouput is 1899. how can i do this? thanks in advance !

Upvotes: 3

Views: 17000

Answers (4)

CodesInChaos
CodesInChaos

Reputation: 108790

When using Math.Round You have two choices for rounding x.5:

Banker's round / Round to even. Avoids biases, by sometimes rounding up(1.5=>2) and sometimes rounding down(0.5=>0), used by default if you don't specify the parameter.

Int32 i=Math.Round(d, MidpointRounding.ToEven);

The rounding you learn at school, where it always rounds towards infinity (0.5=>1, -0.5=>-1)

Int32 i=Math.Round(d, MidpointRounding.AwayFromZero);

Upvotes: 3

Hawxby
Hawxby

Reputation: 2804

Decimal.ToInt32(Math.Round(1899.99M)).ToString();

Upvotes: 0

Assaf
Assaf

Reputation: 1346

Use Math.Round first.

http://msdn.microsoft.com/en-us/library/system.math.round.aspx

Upvotes: 4

ykatchou
ykatchou

Reputation: 3727

Try something like :

Double d = 1899.99;
Int32 i = Math.Round(d);
String retval = i.ToString(CultureInfo.InvariantCulture);

Upvotes: 1

Related Questions