14,268,370 members
Rate this:
See more:
Hello Everyone,

I am a fresher.

I want to convert Double value into a integer value.
but there is a twist in it.

For example:-
3.45 should be converted into 3
3.5 should be converted into 4
3.55 should be converted into 4

Anything below .5 should be converted to its prior digit. and
Anything equal to or above .5 should be converted to its next digit.

Any links or suggestions are welcome..!!
Posted

Rate this:

## Solution 2

Check this.

```static void Main(string[] args)
{
double d1 = 3.49;
double d2 = 3.51;
Console.WriteLine(d1);
Console.WriteLine(d2);
int i1 = Convert.ToInt32(Math.Round(d1, 0, MidpointRounding.ToEven));
int i2 = Convert.ToInt32(Math.Round(d2, 0, MidpointRounding.ToEven));
Console.WriteLine(i1);
Console.WriteLine(i2);
}```
vaibhav mahajan 3-Aug-12 6:30am

it worked for me..!!..;)
Rate this:

## Solution 1

That is how rounding works now, isn't it ?
vaibhav mahajan 3-Aug-12 2:49am

yes...bt

float _otif;

Convert.ToInt32(Convert.ToDouble(_otif);

but above statements are not working..!!
Christian Graus 3-Aug-12 2:51am

Well, your variable has no value, so it's hard to know what you've tried. Plus your code was missing a ).

float _otif = 3.49f;

int n = Convert.ToInt32(Convert.ToDouble(_otif));

works fine. When you get a compiler error, that means your code is broken, not that the conversion is not doing what you want.
vaibhav mahajan 3-Aug-12 3:07am

System.Math.Round(Convert.ToDouble(_otif));

it is not working..!!
Christian Graus 3-Aug-12 3:09am

Honestly, it's working as designed. Buy a damn book and stop telling us that things don't work. This also throws a compiler error. Rounding works EXACTLY as you requested, and you have no examples where it does not, just examples where your code is broken and does not compile.
Rate this:

## Solution 3

simple method is

```double d = 3.49;
int i = Convert.ToInt32(d);```

now i will be equal to 3;

ie if d<3.5 i will be 3
else 4
Rate this:

## Solution 4

If you really need such a (statistically 'poor') rounding behaviour then you have to specify the `MidpointRounding.AwayFromZero` mode in the `Math.Round` call (see, for instance "C# Rounding MidpointRounding.ToEven vs MidpointRounding.AwayFromZero"[^] at `Stack Overflow`)
Rate this:

## Solution 5

```double x=3.499;
int n = Convert.ToInt32(x);
Response.Write(n.ToString());```