Click here to Skip to main content
15,915,603 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have got but I need If decimal part is less then 0.5 result contains minus(-) symbol. and if decimal part is greater then equal 0.5 result contains plus (+) symbol.
I using following code but It returns all the decimal number with (+) symbol.

suppose
456.45 [output should be -.45 ]
456.65 [output should be +.65 ]


thanks in advance

What I have tried:

C#
double value = Convert.ToDouble(textBox5.Text);
            int result = (int)(((decimal)value % 1) * 100);

            if ((result)<0.5)
            {
                textBox6.Text = "-" + result.ToString();
            }
            else
            {
                textBox6.Text = "+" + result.ToString();
            }
Posted
Updated 31-May-20 22:48pm
v3
Comments
ZurdoDev 4-May-16 11:50am    
One easy way is to convert to string and split on the "." and then examine the second part. Probably a better way though.
F-ES Sitecore 4-May-16 12:05pm    
What if the code is run in a locale where "," is the separator?
ZurdoDev 4-May-16 12:08pm    
It won't work.
Philippe Mori 4-May-16 12:39pm    
Learn how to use a debugger.

If you would read carefully your own code, you would see many problems in it. Integer do not have fractionnal part so it make absolutly no sense at all to compare the result with 0.5. Also, you multiply the text box content by 100 but the rest of the code does not take that into account. And we haven't even talk about type conversion....
Philippe Mori 4-May-16 12:40pm    
When you post a question, make the effort to properly format code in a code block. As t, your question does not even worth 1 point.

Try:
C#
double d = 456.45;
double x = d - Math.Truncate(d);
if (x < 0.5) x = -x;
Console.WriteLine(x);
 
Share this answer
 
You're multiplying by 100 and then comparing it to 0.5!

C#
double value = Convert.ToDouble(textBox5.Text);
int result = (int)(((decimal)value % 1) * 100);

if ((result)<50)
{
textBox6.Text = "-" + result.ToString();
}
else
{
textBox6.Text = "+" + result.ToString();
}
 
Share this answer
 
Learn to debug your code. If you step through it what is in "result" for "456.45"? It is 45, yet you are assuming the result is 0.45. When you "% 1" something you get the remainder (.45) which you then multiply by 100 to get 45. I assume you are doing this to make it a valid int, but if you are comparing fractions then you can't use ints.

Secondly, don't use double for fractions with this kind of precision, use decimal as decimal is precise and double is an approximation of your number.

C#
decimal value = Convert.ToDecimal(textBox5.Text);
decimal result = value % 1;

if (result < 0.5M)
 
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