C# round float to the next quarter (0.25) [duplicate] - c#

Is there a simple way in c# to round a decimal to the nearest quarter i.e. x.0, x.25, x.50 x.75
for example 0.21 would round to 0.25, 5.03 would round to 5.0
Thanks in advance for any help.

Multiply it by four, round it as you need to an integer, then divide it by four again:
x = Math.Round (x * 4, MidpointRounding.ToEven) / 4;
The various options for rounding, and their explanations, can be found in this excellent answer here :-)

Alternatively, you can use UltimateRoundingFunction given in this blog:
http://rajputyh.blogspot.in/2014/09/the-ultimate-rounding-function.html
//amountToRound => input amount
//nearestOf => .25 if round to quater, 0.01 for rounding to 1 cent, 1 for rounding to $1
//fairness => btween 0 to 0.9999999___.
// 0 means floor and 0.99999... means ceiling. But for ceiling, I would recommend, Math.Ceiling
// 0.5 = Standard Rounding function. It will round up the border case. i.e. 1.5 to 2 and not 1.
// 0.4999999... non-standard rounding function. Where border case is rounded down. i.e. 1.5 to 1 and not 2.
// 0.75 means first 75% values will be rounded down, rest 25% value will be rounded up.
decimal UltimateRoundingFunction(decimal amountToRound, decimal nearstOf, decimal fairness)
{
return Math.Floor(amountToRound / nearstOf + fairness) * nearstOf;
}
Call below for standard rounding. i.e. 1.125 will be rounded to 1.25
UltimateRoundingFunction(amountToRound, 0.25m, 0.5m);
Call below for rounding down border values. i.e. 1.125 will be rounded to 1.00
UltimateRoundingFunction(amountToRound, 0.25m, 0.4999999999999999m);
So called "Banker's Rounding" is not possible with UltimateRoundingFunction, you have to go with paxdiablo's answer for that support :)

An extension method based on this answer.
namespace j
{
public static class MathHelpers
{
public static decimal RoundToNearestQuarter(this decimal x)
{
return Math.Round(x * 4, MidpointRounding.ToEven) / 4;
}
}
}

Related

Rounding amount up to 2 decimals based on the 3rd number after decimal

I Have to get amounts as below
1099948.275 = 1099948.27,
1099948.276 = 1099948.28,
1099948.274 = 1099948.27
when I use Math.Round(1_099_948.275, 2) I am getting output as 1099948.28 but not 1099948.27. I even tried with awayfromzero and toeven and none of them are working. Any idea?
Is there way to find 3rd number after decimal and if it is 5 just take first two number after decimal else go with mat.round?
This is not how rounding works, neither in C# nor in Math.
By default, anything 5 or more is rounded up, and anything less than 5 is rounded down. This is called "Away from Zero" rounding.
Rounding away from zero
Midpoint values are rounded to the next number away from zero. For example, 3.75 rounds to 3.8, 3.85 rounds to 3.9, -3.75 rounds to -3.8, and -3.85 rounds to -3.9. This form of rounding is represented by the MidpointRounding.AwayFromZero enumeration member.
The other mode is rounding to the closest even number. This is half of what you're looking for. In this way, when something ends with a "5" (the midpoint), that number is rounded to the closest even number, which could be up or down. This is done to distribute out the chances a rounding affects one particular party in a monetary transaction.
Rounding to nearest even, or banker's rounding
Midpoint values are rounded to the nearest even number. For example, both 3.75 and 3.85 round to 3.8, and both -3.75 and -3.85 round to -3.8. This form of rounding is represented by the MidpointRounding.ToEven enumeration member.
The source for both of the above quotes are on the Math.Round documentation page.
There is no supported rounding system that always rounds a 5 down. You'd need to inspect the value first to see if the last digit is a 5, then truncate the digit rather than attempt rounding.
One could implement your own rounding strategy:
public static double RoundDown(double value, int precision)
{
var rounded = Math.Ceiling(value * Math.Pow(10,precision) - 0.5) / Math.Pow(10,precision);
return rounded;
}
public static decimal RoundDown(decimal value, int precision)
{
decimal scale = 1;
for(int i=0;i<precision;i++)
{
scale *= 10;
}
var rounded = Math.Ceiling(value * scale - 0.5M) / scale;
return rounded;
}
Usage:
var values = new double[] {1099948.275, 1099948.276, 1099948.274 };
Console.WriteLine("double:");
foreach(var value in values)
{
var rounded = RoundDown(value, 2);
Console.WriteLine($"{value} = {rounded}");
}
Console.WriteLine("decimal:");
var values_m = new decimal[] {1099948.275M, 1099948.276M, 1099948.274M };
foreach(var value in values_m)
{
var rounded = RoundDown(value, 2);
Console.WriteLine($"{value} = {rounded}");
}
double:
1099948.275 = 1099948.27
1099948.276 = 1099948.28
1099948.274 = 1099948.27
decimal:
1099948.275 = 1099948.27
1099948.276 = 1099948.28
1099948.274 = 1099948.27
You can get what you need by subtracting 0.001 from the number before rounding it
Math.Round(1099948.275-0.001,2)
Edit:
to answer some of the comments
Math.Round(1099948.270-0.001,2) will still give the correct answer which is 1099948.27
similarly for any other number.
negative numbers may need to be handled differently depending on requirements.

Round a floating point number to next coming number

I want to round off a decimal number to the next higher number nn c#.
for example:
23.3 should become 24
25.8 should become 26
26.1 should become 27
currently i am using this code but it is not fulfilling my requirements.
double pages = Math.Floor((float)anyNumber / 5);
Math.Floor rounds down, use Math.Ceiling to round up:
double pages = Math.Ceiling( anyNumber / 5.0 );
Math.Ceiling will do what you want...
double pages = Math.Ceiling((float)anyNumber / 5);
as an aside, you might choose to cast to double instead of float to avoid extra implicit casts from float to double:
double pages = Math.Ceiling((double)anyNumber / 5d);

C# - Decimal to integer and round depending on value

I'm trying convert a decimal into integer and want to round the value up or down depending on the situation.
Basically example is:
12/3 = 4 so should round to 4
11/3 = 3.66666 so should round to 4
10/3 = 3 = 3.33333 so should round to 3
9/3 = 3 so should round to 3
Whatever I found on the internet always rounds down or always rounds up, never makes a judgment call based on the numbers.
If x is the number you want to round and you want the "normal" rounding behavior (so that .5 always gets rounded up), you need to use Math.Round(x, MidpointRounding.AwayFromZero). Note that if you are actually computing fractions and the numerator and denominator are integers, you need to cast one of them to double first (otherwise, the division operator will produce an integer that is rounded down), and that if you want the result to be an int, you need to cast the result of Round():
int a = 5;
int b = 2;
double answer = (int) Math.Round(a / (double) b, MidpointRounding.AwayFromZero);
Math.Round(value) should do what you want. Examples console app code to demonstrate:
Console.Write("12 / 3 = ");
Console.WriteLine((int)Math.Round(12d / 3d));
Console.WriteLine();
Console.Write("11 / 3 = ");
Console.WriteLine((int)Math.Round(11d / 3d));
Console.WriteLine();
Console.Write("10 / 3 = ");
Console.WriteLine((int)Math.Round(10d / 3d));
Console.WriteLine();
Console.Write("9 / 3 = ");
Console.WriteLine((int)Math.Round(9d / 3d));
Console.WriteLine();
Console.ReadKey();
Does Math.Round(d) do what you require?
Return Value:
The integer nearest parameter d. If the fractional component of d is halfway between two integers, one of which is even and the other odd, the even number is returned. Note that this method returns a Decimal instead of an integral type.
Check out the Round reference page
You could try this
Math.Round(d, 0, MidpointRounding.AwayFromZero)
Sometime, people add 0.5 to the number before converting to int.

Is there a way to floor/ceil based on whether the value is over 0.5 or under?

I am trying to round my values so that if it's 0.5 or greater, it becomes 1, else it becomes 0. For example:
3.7 -> 4;
1.3 -> 1;
2.5 -> 3;
...
Any ideas?
Math.Round(3.7,MidpointRounding.AwayFromZero);
http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx
In the above, I made use of AwayFromZero for rounding because the default is Banker's rounding, so if the fraction is 0.5, it is rounded to nearest even. So 3.5 becomes 4 (nearest even), but 2.5 becomes 2 (nearest even). So you choose a different method as shown above to make 3.5 to 4 and 2.5 to 3.
The simplest way is add 0.5 to the input, then cast to int.
I arrived last, so I'll tell something different. You round 0.5 to 1 by not using double! Use decimals. double aren't good to have "exact" numbers.
Launch this piece of code and have fun (note that there is/was a "bug" in mono on numbers like 0.49999999999999994, so to run it on ideone I had to modify it a little to try to round 1.5: http://ideone.com/57XAYV)
public static void Main()
{
double d = 1.0;
d -= 0.3;
d -= 0.2;
Console.WriteLine("Standard formatting: {0}", d); // 0.5
Console.WriteLine("Internal Representation: {0:r}", d); // 0.49999999999999994
Console.WriteLine("Console WriteLine 0 decimals: {0:0}", d); // 1
Console.WriteLine("0 decimals Math.Round: {0}", Math.Round(d, MidpointRounding.AwayFromZero)); // 0
Console.WriteLine("15 decimals then 0 decimals Math.Round: {0}", Math.Round(Math.Round(d, 15, MidpointRounding.AwayFromZero), MidpointRounding.AwayFromZero)); // 1
}
Round-Up
Math.Round(3.5, 0, MidpointRounding.AwayFromZero) -> 4
Round Down
Math.Round(3.5, 0, MidpointRounding.ToEven) -> 3

Round a decimal to the nearest quarter in C#

Is there a simple way in c# to round a decimal to the nearest quarter i.e. x.0, x.25, x.50 x.75
for example 0.21 would round to 0.25, 5.03 would round to 5.0
Thanks in advance for any help.
Multiply it by four, round it as you need to an integer, then divide it by four again:
x = Math.Round (x * 4, MidpointRounding.ToEven) / 4;
The various options for rounding, and their explanations, can be found in this excellent answer here :-)
Alternatively, you can use UltimateRoundingFunction given in this blog:
http://rajputyh.blogspot.in/2014/09/the-ultimate-rounding-function.html
//amountToRound => input amount
//nearestOf => .25 if round to quater, 0.01 for rounding to 1 cent, 1 for rounding to $1
//fairness => btween 0 to 0.9999999___.
// 0 means floor and 0.99999... means ceiling. But for ceiling, I would recommend, Math.Ceiling
// 0.5 = Standard Rounding function. It will round up the border case. i.e. 1.5 to 2 and not 1.
// 0.4999999... non-standard rounding function. Where border case is rounded down. i.e. 1.5 to 1 and not 2.
// 0.75 means first 75% values will be rounded down, rest 25% value will be rounded up.
decimal UltimateRoundingFunction(decimal amountToRound, decimal nearstOf, decimal fairness)
{
return Math.Floor(amountToRound / nearstOf + fairness) * nearstOf;
}
Call below for standard rounding. i.e. 1.125 will be rounded to 1.25
UltimateRoundingFunction(amountToRound, 0.25m, 0.5m);
Call below for rounding down border values. i.e. 1.125 will be rounded to 1.00
UltimateRoundingFunction(amountToRound, 0.25m, 0.4999999999999999m);
So called "Banker's Rounding" is not possible with UltimateRoundingFunction, you have to go with paxdiablo's answer for that support :)
An extension method based on this answer.
namespace j
{
public static class MathHelpers
{
public static decimal RoundToNearestQuarter(this decimal x)
{
return Math.Round(x * 4, MidpointRounding.ToEven) / 4;
}
}
}

Categories