C# - Rounding Down to Nearest Integer

C#

C# Problem Overview


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 an int. At the same time, I cannot just use Convert.ToInt32 because of its rounding behavior. I always want the lowest whole number. However, I'm not sure how.

C# Solutions


Solution 1 - C#

Just try this..

 int interval = Convert.ToInt32(Math.Floor(different/increment));

Solution 2 - C#

You can also just simply cast the result to int. This will truncate the number.

int interval = (int)(difference / increment);

Solution 3 - C#

Use the static Math class:

int interval = (int)Math.Floor(difference/increment);

Math.Floor() will round down to the nearest integer.

Solution 4 - C#

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 - C#

Convert.ToSingle(); 

is another method

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser70192View Question on Stackoverflow
Solution 1 - C#praveenView Answer on Stackoverflow
Solution 2 - C#monoh_View Answer on Stackoverflow
Solution 3 - C#Alexander DerckView Answer on Stackoverflow
Solution 4 - C#user5914638View Answer on Stackoverflow
Solution 5 - C#Chiranjeevi KandelView Answer on Stackoverflow