Force Calculation to Round Up in C# [duplicate] - c#

I want to round up double to int.
Eg,
double a=0.4, b=0.5;
I want to change them both to integer.
so that
int aa=0, bb=1;
aa is from a and bb is from b.
Any formula to do that?

Use Math.Ceiling to round up
Math.Ceiling(0.5); // 1
Use Math.Round to just round
Math.Round(0.5, MidpointRounding.AwayFromZero); // 1
And Math.Floor to round down
Math.Floor(0.5); // 0

Check out Math.Round. You can then cast the result to an int.

The .NET framework uses banker's rounding in Math.Round by default. You should use this overload:
Math.Round(0.5d, MidpointRounding.AwayFromZero) //1
Math.Round(0.4d, MidpointRounding.AwayFromZero) //0

Math.Round
Rounds a double-precision floating-point value to the nearest integral value.

Use a function in place of MidpointRounding.AwayFromZero:
myRound(1.11125,4)
Answer:- 1.1114
public static Double myRound(Double Value, int places = 1000)
{
Double myvalue = (Double)Value;
if (places == 1000)
{
if (myvalue - (int)myvalue == 0.5)
{
myvalue = myvalue + 0.1;
return (Double)Math.Round(myvalue);
}
return (Double)Math.Round(myvalue);
places = myvalue.ToString().Substring(myvalue.ToString().IndexOf(".") + 1).Length - 1;
} if ((myvalue * Math.Pow(10, places)) - (int)(myvalue * Math.Pow(10, places)) > 0.49)
{
myvalue = (myvalue * Math.Pow(10, places + 1)) + 1;
myvalue = (myvalue / Math.Pow(10, places + 1));
}
return (Double)Math.Round(myvalue, places);
}

Just some adjusting #BrunoLM's answer with more samples :
Math.Round(0.4); // =0
Math.Round(0.5); // =0
Math.Round(0.6); // =1
Math.Round(0.4, MidpointRounding.AwayFromZero); // = 0
Math.Round(0.5, MidpointRounding.AwayFromZero); // = 1
Math.Round(0.6, MidpointRounding.AwayFromZero); // = 1
Math.Round(0.4, MidpointRounding.ToEven); // = 0
Math.Round(0.5, MidpointRounding.ToEven); // = 0
Math.Round(0.6, MidpointRounding.ToEven); // = 1

Math.Round(0.5) returns zero due to floating point rounding errors, so you'll need to add a rounding error amount to the original value to ensure it doesn't round down, eg.
Console.WriteLine(Math.Round(0.5, 0).ToString()); // outputs 0 (!!)
Console.WriteLine(Math.Round(1.5, 0).ToString()); // outputs 2
Console.WriteLine(Math.Round(0.5 + 0.00000001, 0).ToString()); // outputs 1
Console.WriteLine(Math.Round(1.5 + 0.00000001, 0).ToString()); // outputs 2
Console.ReadKey();

Another option:
string strVal = "32.11"; // will return 33
// string strVal = "32.00" // returns 32
// string strVal = "32.98" // returns 33
string[] valStr = strVal.Split('.');
int32 leftSide = Convert.ToInt32(valStr[0]);
int32 rightSide = Convert.ToInt32(valStr[1]);
if (rightSide > 0)
leftSide = leftSide + 1;
return (leftSide);

It is also possible to round negative integers
// performing d = c * 3/4 where d can be pos or neg
d = ((c * a) + ((c>0? (b>>1):-(b>>1)))) / b;
// explanation:
// 1.) multiply: c * a
// 2.) if c is negative: (c>0? subtract half of the dividend
// (b>>1) is bit shift right = (b/2)
// if c is positive: else add half of the dividend
// 3.) do the division
// on a C51/52 (8bit embedded) or similar like ATmega the below code may execute in approx 12cpu cycles (not tested)
Extended from a tip somewhere else in here. Sorry, missed from where.
/* Example test: integer rounding example including negative*/
#include <stdio.h>
#include <string.h>
int main () {
//rounding negative int
// doing something like d = c * 3/4
int a=3;
int b=4;
int c=-5;
int d;
int s=c;
int e=c+10;
for(int f=s; f<=e; f++) {
printf("%d\t",f);
double cd=f, ad=a, bd=b , dd;
// d = c * 3/4 with double
dd = cd * ad / bd;
printf("%.2f\t",dd);
printf("%.1f\t",dd);
printf("%.0f\t",dd);
// try again with typecast have used that a lot in Borland C++ 35 years ago....... maybe evolution has overtaken it ;) ***
// doing div before mul on purpose
dd =(double)c * ((double)a / (double)b);
printf("%.2f\t",dd);
c=f;
// d = c * 3/4 with integer rounding
d = ((c * a) + ((c>0? (b>>1):-(b>>1)))) / b;
printf("%d\t",d);
puts("");
}
return 0;
}
/* test output
in 2f 1f 0f cast int
-5 -3.75 -3.8 -4 -3.75 -4
-4 -3.00 -3.0 -3 -3.75 -3
-3 -2.25 -2.2 -2 -3.00 -2
-2 -1.50 -1.5 -2 -2.25 -2
-1 -0.75 -0.8 -1 -1.50 -1
0 0.00 0.0 0 -0.75 0
1 0.75 0.8 1 0.00 1
2 1.50 1.5 2 0.75 2
3 2.25 2.2 2 1.50 2
4 3.00 3.0 3 2.25 3
5 3.75 3.8 4 3.00
// by the way evolution:
// Is there any decent small integer library out there for that by now?

It is simple. So follow this code.
decimal d = 10.5;
int roundNumber = (int)Math.Floor(d + 0.5);
Result is 11

Related

c# Math function not calulating

I have a simple math function
private int Doyle(LogArguments args)
{
return Convert.ToInt32(Math.Round(Math.Pow((args.Diameter - 4) , 2.0) * (args.Length / 16),0));
}
that should always return an int > 0 but my problem is if args.Length <= 16 it args.Length/16 = 0.
I have tried:
decimal d = args.length/16
and double d = args.length/16;
which both turn out to 0 when Length <16
If args.length is an int you are doing integer division regardless of what the type of the output variable is. To force decimal division the simplest way is to specify a decimal literal in the denominator:
decimal d = args.length / 16M;
Or for a double use a floating-point literal:
double d = args.length / 16.0;
double d = args.length/16;
which both turn out to 0 when Length <16
That is because args.Length and 16 are both integers. You get integer division (result 0), which is then cast to a double. Instead, try
double d = args.length/16.0;
If you are trying to multiply by a float value such as this:
5 / 16 = 0.3125
Then you should turn (args.Length / 16) into (args.Length / 16f).
This will force the division to be does as a floating point, and keep any remainder. Without the f added, it will do it as an integer division which truncates the remainder, so any value less than 16 will be less than 1 and get reduced to 0.

Rounding integers to nearest multiple of 10 [duplicate]

This question already has answers here:
Returning the nearest multiple value of a number
(6 answers)
Closed 3 years ago.
I am trying to figure out how to round prices - both ways. For example:
Round down
43 becomes 40
143 becomes 140
1433 becomes 1430
Round up
43 becomes 50
143 becomes 150
1433 becomes 1440
I have the situation where I have a price range of say:
£143 - £193
of which I want to show as:
£140 - £200
as it looks a lot cleaner
Any ideas on how I can achieve this?
I would just create a couple methods;
int RoundUp(int toRound)
{
if (toRound % 10 == 0) return toRound;
return (10 - toRound % 10) + toRound;
}
int RoundDown(int toRound)
{
return toRound - toRound % 10;
}
Modulus gives us the remainder, in the case of rounding up 10 - r takes you to the nearest tenth, to round down you just subtract r. Pretty straight forward.
You don't need to use modulus (%) or floating point...
This works:
public static int RoundUp(int value)
{
return 10*((value + 9)/10);
}
public static int RoundDown(int value)
{
return 10*(value/10);
}
This code rounds to the nearest multiple of 10:
int RoundNum(int num)
{
int rem = num % 10;
return rem >= 5 ? (num - rem + 10) : (num - rem);
}
Very simple usage :
Console.WriteLine(RoundNum(143)); // prints 140
Console.WriteLine(RoundNum(193)); // prints 190
A general method to round a number to a multiple of another number, rounding away from zero.
For integer
int RoundNum(int num, int step)
{
if (num >= 0)
return ((num + (step / 2)) / step) * step;
else
return ((num - (step / 2)) / step) * step;
}
For float
float RoundNum(float num, float step)
{
if (num >= 0)
return floor((num + step / 2) / step) * step;
else
return ceil((num - step / 2) / step) * step;
}
I know some parts might seem counter-intuitive or not very optimized. I tried casting (num + step / 2) to an int, but this gave wrong results for negative floats ((int) -12.0000 = -11 and such). Anyways these are a few cases I tested:
any number rounded to step 1 should be itself
-3 rounded to step 2 = -4
-2 rounded to step 2 = -2
3 rounded to step 2 = 4
2 rounded to step 2 = 2
-2.3 rounded to step 0.2 = -2.4
-2.4 rounded to step 0.2 = -2.4
2.3 rounded to step 0.2 = 2.4
2.4 rounded to step 0.2 = 2.4
Divide the number by 10.
number = number / 10;
Math.Ceiling(number);//round up
Math.Round(number);//round down
Then multiply by 10.
number = number * 10;
public static int Round(int n)
{
// Smaller multiple
int a = (n / 10) * 10;
// Larger multiple
int b = a + 10;
// Return of closest of two
return (n - a > b - n) ? b : a;
}

C# Bug in Modulo Operator %

Solving one bug I came to some interesting discoveries.
The result of this procedure
static void Main(string[] args)
{
int i4 = 4;
Console.WriteLine("int i4 = 4;");
Console.WriteLine("i4 % 1 = {0}", i4 % 1);
double d4 = 4.0;
Console.WriteLine("double d4 = 4.0;");
Console.WriteLine("d4 % 1 = {0}", d4 % 1);
Console.WriteLine("-----------------------------------------------------------");
int i64 = 64;
double dCubeRootOf64 = Math.Pow(i64, 1.0 / 3.0);
Console.WriteLine("int i64 = 64;");
Console.WriteLine("double dCubeRootOf64 = Math.Pow(i64, 1.0 / 3.0) = {0}", dCubeRootOf64);
Console.WriteLine("dCubeRootOf64 = {0}", dCubeRootOf64);
Console.WriteLine("dCubeRootOf64 % 1 = {0} ?????????????? Why 1. ??????????", dCubeRootOf64 % 1);
Console.ReadLine();
}
is
int i4 = 4;
i4 % 1 = 0
double d4 = 4.0;
d4 % 1 = 0
-----------------------------------------------------------
int i64 = 64;
double dCubeRootOf64 = Math.Pow(i64, 1.0 / 3.0) = 4
dCubeRootOf64 = 4
dCubeRootOf64 % 1 = 1 ?????????????? Why 1. ??????????
int 4 % 1 = 0 -- correct
double 4.0 % 1 = 0 -- correct
But bug is in:
Math.Pow(64, 1.0 / 3.0) % 1 = 1
Cube root from 64 is 4. Why is in that case 4 % 1 = 1?
Math.Pow(64, 1.0 / 3.0) returns 3.9999999999999996.
This gets rounded to 4 when displayed.
Taking it modulo 1 returns 0.99999999999999956, which is similarly rounded to 1 when displayed.
You can see the true values by adding .ToString("R")
dCubeRootOf64 % 1 = 1 returns 1 instead 0; cause Math.Pow(i64, 1.0 / 3.0) returns 3.9999999999999996 and 3.9999999999999996 % 1 returns 0.99999999999999956 which in turn getting rounded to 1.
Thus the result 1.

Meaning of "%" operation in C# for the numeric type double

Recently I discovered that C#'s operator % is applicable to double. Tried some things out, and after all came up with this test:
class Program
{
static void test(double a, double b)
{
if (a % b != a - b * Math.Truncate(a / b))
{
Console.WriteLine(a + ", " + b);
}
}
static void Main(string[] args)
{
test(2.5, 7);
test(-6.7, -3);
test(8.7, 4);
//...
}
}
Everything in this test works.
Is a % b always equivalent to a - b*Math.Round(a/b)? If not, please explain to me how this operator really works.
EDIT: Answering to James L, I understand that this is a modulo operator and everything. I'm curious only about how it works with double, integers I understand.
The modulus operator works on floating point values in the same way as it does for integers. So consider a simple example:
4.5 % 2.1
Now, 4.5/2.1 is approximately equal to 2.142857
So, the integer part of the division is 2. Subtract 2*2.1 from 4.5 and you have the remainer, 0.3.
Of course, this process is subject to floating point representability issues so beware – you may see unexpected results. For example, see this question asked here on Stack Overflow: Floating Point Arithmetic - Modulo Operator on Double Type
Is a % b always equivalent to a - b*Math.Round(a/b)?
No it is not. Here is a simple counter example:
static double f(double a, double b)
{
return a - b * Math.Round(a / b);
}
static void Main(string[] args)
{
Console.WriteLine(1.9 % 1.0);
Console.WriteLine(f(1.9, 1.0));
Console.ReadLine();
}
As to the precise details of how the modulus operator is specified you need to refer to the C# specification – earlNameless's answer gives you a link to that.
It is my understanding that a % b is essentially equivalent, modulo floating point precision, to a - b*Math.Truncate(a/b).
From C# Language Specifications page 200:
Floating-point remainder:
float operator %(float x, float y);
double operator %(double x, double y);
The following table lists the results of all possible combinations of nonzero finite values, zeros, infinities, and NaN’s. In the table, x and y are positive finite values. z is the result of x % y and is computed as x – n * y, rounded to the nearest representable value, where n is the largest integer that is less than or equal to x / y. This method of computing the remainder is analogous to that used for integer operands, but differs from the IEC 60559 definition (in which n is the integer closest to x / y).
From the MSDN page :
The modulus operator (%) computes the remainder after dividing its
first operand by its second. All numeric types have predefined modulus
operators.
And
Note the round-off errors associated with the double type.
Searching with the phrase "modulo floating point c#" brings up quite a few entries in Stack Overflow, most of them explaining nicely how floating point precision complicates things. I did not recognize any suggestion for a simple practical way to handle that. What I came up with for my own purposes is the following modulo function:
public static double modulo( double a, double b, double num_sig_digits = 14 )
{
double int_closest_to_ratio
, abs_val_of_residue
;
if ( double.IsNaN( a )
|| double.IsNaN( b )
|| 0 == b
)
{
throw new Exception( "function modulo called with a or b == NaN or b == 0" );
}
if ( b == Math.Floor( b ) )
{
return (a % b);
}
else
{
int_closest_to_ratio = Math.Round( a / b );
abs_val_of_residue = Math.Abs( a - int_closest_to_ratio * b );
if ( abs_val_of_residue < Math.Pow( 10.0, -num_sig_digits ) )
{
return 0.0;
}
else
{
return abs_val_of_residue * Math.Sign( a );
}
}
}
Following are some sample results:
modulo( 0.5, 0.1, 17 ) = 0
modulo( 0.5, -0.1, 16 ) = 0
modulo( -0.5, 0.1, 15 ) = 0
modulo( -0.5, -0.1, 14 ) = 0
modulo( 0.52, 0.1, 16 ) = 0.02
modulo( 0.53, -0.1, 15 ) = 0.03
modulo( -0.54, 0.1, 14 ) = -0.04
modulo( -0.55, -0.1, 13 ) = -0.05
modulo( 2.5, 1.01, 17 ) = 0.48
modulo( 2.5, -1.01, 16 ) = 0.48
modulo( -2.5, 1.01, 15 ) = -0.48
modulo( -2.5, -1.01, 14 ) = -0.48
modulo( 0.599999999999977, 0.1, 16 ) = 2.35367281220533E-14
modulo( 0.599999999999977, 0.1, 15 ) = 2.35367281220533E-14
modulo( 0.599999999999977, 0.1, 14 ) = 2.35367281220533E-14
modulo( 0.599999999999977, 0.1, 13 ) = 0
modulo( 0.599999999999977, 0.1, 12 ) = 0

How to round up value C# to the nearest integer?

I want to round up double to int.
Eg,
double a=0.4, b=0.5;
I want to change them both to integer.
so that
int aa=0, bb=1;
aa is from a and bb is from b.
Any formula to do that?
Use Math.Ceiling to round up
Math.Ceiling(0.5); // 1
Use Math.Round to just round
Math.Round(0.5, MidpointRounding.AwayFromZero); // 1
And Math.Floor to round down
Math.Floor(0.5); // 0
Check out Math.Round. You can then cast the result to an int.
The .NET framework uses banker's rounding in Math.Round by default. You should use this overload:
Math.Round(0.5d, MidpointRounding.AwayFromZero) //1
Math.Round(0.4d, MidpointRounding.AwayFromZero) //0
Math.Round
Rounds a double-precision floating-point value to the nearest integral value.
Use a function in place of MidpointRounding.AwayFromZero:
myRound(1.11125,4)
Answer:- 1.1114
public static Double myRound(Double Value, int places = 1000)
{
Double myvalue = (Double)Value;
if (places == 1000)
{
if (myvalue - (int)myvalue == 0.5)
{
myvalue = myvalue + 0.1;
return (Double)Math.Round(myvalue);
}
return (Double)Math.Round(myvalue);
places = myvalue.ToString().Substring(myvalue.ToString().IndexOf(".") + 1).Length - 1;
} if ((myvalue * Math.Pow(10, places)) - (int)(myvalue * Math.Pow(10, places)) > 0.49)
{
myvalue = (myvalue * Math.Pow(10, places + 1)) + 1;
myvalue = (myvalue / Math.Pow(10, places + 1));
}
return (Double)Math.Round(myvalue, places);
}
Just some adjusting #BrunoLM's answer with more samples :
Math.Round(0.4); // =0
Math.Round(0.5); // =0
Math.Round(0.6); // =1
Math.Round(0.4, MidpointRounding.AwayFromZero); // = 0
Math.Round(0.5, MidpointRounding.AwayFromZero); // = 1
Math.Round(0.6, MidpointRounding.AwayFromZero); // = 1
Math.Round(0.4, MidpointRounding.ToEven); // = 0
Math.Round(0.5, MidpointRounding.ToEven); // = 0
Math.Round(0.6, MidpointRounding.ToEven); // = 1
Math.Round(0.5) returns zero due to floating point rounding errors, so you'll need to add a rounding error amount to the original value to ensure it doesn't round down, eg.
Console.WriteLine(Math.Round(0.5, 0).ToString()); // outputs 0 (!!)
Console.WriteLine(Math.Round(1.5, 0).ToString()); // outputs 2
Console.WriteLine(Math.Round(0.5 + 0.00000001, 0).ToString()); // outputs 1
Console.WriteLine(Math.Round(1.5 + 0.00000001, 0).ToString()); // outputs 2
Console.ReadKey();
Another option:
string strVal = "32.11"; // will return 33
// string strVal = "32.00" // returns 32
// string strVal = "32.98" // returns 33
string[] valStr = strVal.Split('.');
int32 leftSide = Convert.ToInt32(valStr[0]);
int32 rightSide = Convert.ToInt32(valStr[1]);
if (rightSide > 0)
leftSide = leftSide + 1;
return (leftSide);
It is also possible to round negative integers
// performing d = c * 3/4 where d can be pos or neg
d = ((c * a) + ((c>0? (b>>1):-(b>>1)))) / b;
// explanation:
// 1.) multiply: c * a
// 2.) if c is negative: (c>0? subtract half of the dividend
// (b>>1) is bit shift right = (b/2)
// if c is positive: else add half of the dividend
// 3.) do the division
// on a C51/52 (8bit embedded) or similar like ATmega the below code may execute in approx 12cpu cycles (not tested)
Extended from a tip somewhere else in here. Sorry, missed from where.
/* Example test: integer rounding example including negative*/
#include <stdio.h>
#include <string.h>
int main () {
//rounding negative int
// doing something like d = c * 3/4
int a=3;
int b=4;
int c=-5;
int d;
int s=c;
int e=c+10;
for(int f=s; f<=e; f++) {
printf("%d\t",f);
double cd=f, ad=a, bd=b , dd;
// d = c * 3/4 with double
dd = cd * ad / bd;
printf("%.2f\t",dd);
printf("%.1f\t",dd);
printf("%.0f\t",dd);
// try again with typecast have used that a lot in Borland C++ 35 years ago....... maybe evolution has overtaken it ;) ***
// doing div before mul on purpose
dd =(double)c * ((double)a / (double)b);
printf("%.2f\t",dd);
c=f;
// d = c * 3/4 with integer rounding
d = ((c * a) + ((c>0? (b>>1):-(b>>1)))) / b;
printf("%d\t",d);
puts("");
}
return 0;
}
/* test output
in 2f 1f 0f cast int
-5 -3.75 -3.8 -4 -3.75 -4
-4 -3.00 -3.0 -3 -3.75 -3
-3 -2.25 -2.2 -2 -3.00 -2
-2 -1.50 -1.5 -2 -2.25 -2
-1 -0.75 -0.8 -1 -1.50 -1
0 0.00 0.0 0 -0.75 0
1 0.75 0.8 1 0.00 1
2 1.50 1.5 2 0.75 2
3 2.25 2.2 2 1.50 2
4 3.00 3.0 3 2.25 3
5 3.75 3.8 4 3.00
// by the way evolution:
// Is there any decent small integer library out there for that by now?
It is simple. So follow this code.
decimal d = 10.5;
int roundNumber = (int)Math.Floor(d + 0.5);
Result is 11

Categories

Resources