Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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

Check this.

C#
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();
        }
 
Share this answer
 
Comments
vaibhav mahajan 3-Aug-12 6:30am    
it worked for me..!!..;)
That is how rounding works now, isn't it ?
 
Share this answer
 
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.
simple method is

C#
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
 
Share this answer
 
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)
 
Share this answer
 
C#
double x=3.499;
int n = Convert.ToInt32(x);
Response.Write(n.ToString());
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900