Click here to Skip to main content
14,268,370 members
Rate this:
Please Sign up or sign in to vote.
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:
Please Sign up or sign in to vote.

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);
            Console.Read();
        }
   
Comments
vaibhav mahajan 3-Aug-12 6:30am
   
it worked for me..!!..;)
Rate this:
Please Sign up or sign in to vote.

Solution 1

That is how rounding works now, isn't it ?
   
Comments
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:
Please Sign up or sign in to vote.

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:
Please Sign up or sign in to vote.

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:
Please Sign up or sign in to vote.

Solution 5

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

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100