tags:

views:

69

answers:

1

I want to divide size of a control with a size of a form and want to gets its floor value. I was thinking what would be returned when I try to divide an integer with an integer and store its result again in an integer.

I want only floor value. I tried to use Math.Floor, Math.Truncate but it shows me an error that call between following methods is ambigious because compiler is not able to understand what type of value will be returned after diving i.e. decimal or Double.

Will it return me floor value if i dont use any such function. I want only floor value.

        Nullable<int> PanelCountInSingleRow = null;
        Nullable<int> widthRemainder = null;

        //setting the size of the panel
        CurrentControlSize = PanelView.Size;
        //Calculate no of Panels that can come in a single row.
        PanelCountInSingleRow = Math.Floor(this.Size.Width / CurrentControlSize.Width);
+2  A: 

Integer division rounds toward 0. Not quite the same as taking the floor (due to negative numbers rounding "up" toward 0) but I'm assuming your sizes are non-negative anyway. From the C# 4 spec, section 7.8.2:

The division rounds the result towards zero. Thus the absolute value of the result is the largest possible integer that is less than or equal to the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs.

(Note that this is specifically for integer division. Obviously floating point division doesn't do this!)

So basically you should be able to remove the Math.Floor call.

If you want to get the remainder as well, you could use Math.DivRem:

int remainder;
int count = Math.DivRem(Size.Width, CurrentControlSize.Width, out remainder);
Jon Skeet
@Jon: Thanks for the info, I have 1 More Question on your edit of remainder. Will it return me some fixed decimal value or something else. eg. In this case 10/3 ? remainder would be 333333 up to ?, in 5/2 ? 5 as 50 or what
Shantanu Gupta
@Shantanu: No, it will return the *remainder* - so for 10/3, the remainder would be 1, because that's what's left after dividing 10 by 3. Ditto 5/2 is 2 remainder 1. 8 / 2 would be 4 remainder 0, 11 / 3 would be 3 remainder 2 etc. See the docs for more details.
Jon Skeet
@Jon, oops sry, didn't thought what i am asking. Yes you are right.
Shantanu Gupta