C# - Rounding Down to Nearest Integer
107,654
Solution 1
Just try this..
int interval = Convert.ToInt32(Math.Floor(different/increment));
Solution 2
You can also just simply cast the result to int
. This will truncate the number.
int interval = (int)(difference / increment);
Solution 3
Use the static Math
class:
int interval = (int)Math.Floor(difference/increment);
Math.Floor()
will round down to the nearest integer.
Solution 4
The Math.Floor()
function should do the trick:
int interval = (int)Math.Floor(difference / increment);
See also: https://msdn.microsoft.com/de-de/library/e0b5f0xb%28v=vs.110%29.aspx
Solution 5
Convert.ToSingle();
is another method
Related videos on Youtube
Author by
user70192
Updated on July 09, 2022Comments
-
user70192 almost 2 years
I have a C# app that is calculating some numbers. I need to round down.
var increment = 1.25; var result = 50.45 - 23.70; // equals 26.75 int interval = difference / increment; // result is 21.4. However, I just want 21
I have to get the
interval
to anint
. At the same time, I cannot just useConvert.ToInt32
because of its rounding behavior. I always want the lowest whole number. However, I'm not sure how. -
Rob over 8 yearsIt returns a double = so why is there no compiler warning?
-
Alexander Derck over 8 years@Rob Just casting it to an
int
should do the trick, the documentation is a bit confusing "The largest integer less than or equal to d." but it does indeed return a double -
Antonín Lejsek over 8 yearsYes, this is the fastest option.
-
LinusR about 6 yearsNote, this is only equivalent for positive numbers. Converting to int will bring the value towards zero. If you want
-1.1
to round down to-2
, you needMath.Floor()
. -
user2455808 almost 5 yearswhat if this is a double and you have 1e300 numbers? :)