Click here to Skip to main content
15,878,959 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone!

I am currently trying round figure out how much a value out of 20 is. For instance,

-5 out of 20 would be -1.
5 out of 20 would be 1.

25 out of 20 would be 2.
-25 out of 20 would be -2

However, when I do that:

C#
int newValue = (int)Number / 20


-5 returns as 0. Which is normal, however, I need the negative value -1. Does anyone have any ideas? This is driving me insane, and doing this manually:

C#
if(Number.StartsWith "-")


Would not make any logic for me, and not for my program either. Please help!
Posted
Comments
lewax00 3-May-13 17:06pm    
I don't really get what you're trying to do here, but integer division always truncates. So: -5/20 = -0.25 which will truncate to -0, which is the same as 0. As far as checking if a value is negative though, just check if it's less than 0.

1 solution

For positive numbers use Math.Ceiling Method (Double)[^] and for negative numbers use Math.Floor Method (Double)[^].
So:
C#
const double newValue = Number / 20.0;
double outOfTwenty = 0.0;

if (newValue >= 0.0)
    outOfTwenty = Math.Ceiling(NewValue);
else
    outOfTwenty = Math.Floor(NewValue);
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 3-May-13 17:07pm    
Right, a 5. You could also have mentioned Math.Round, for comparison.
—SA
Yvar Birx 3-May-13 17:18pm    
-16 returns to 0?

-16 / 20 = -0.8?
André Kraak 3-May-13 17:22pm    
Math.Floor(-0.8) should be -1.0
Yvar Birx 3-May-13 17:23pm    
if (Number > 0)
{
Number = Math.Ceiling(Number );
}
else
{
Number = Math.Floor(Number );
}
Yvar Birx 3-May-13 17:50pm    
:S

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