Number Rounding Methods
There are 3 different methods that can be used to round decimal numbers of type double or decimal to integers.
Round, Ceiling and Floor Methods
The Ceiling method rounds the decimal number sent to it to the largest integer. So it rounds up.
The floor method rounds the decimal number to the smallest integer. So it rounds down.
The round method rounds a decimal number to the nearest integer. For example, it rounds 3.44 to 3 and 3.55 to 4.
Sample:
decimal number = decimal.Parse(textBox1.Text);
decimal s1 = Math.Ceiling(number);
label1.Text = s1.ToString();
decimal s2= Math.Floor(number);
label6.Text = s2.ToString();
decimal s3= Math.Round(number);
label4.Text = s3.ToString();
Max and Min Methods
The Max method returns the larger of the two numbers given to it. The min method returns the smaller number.
Both methods can be used for all variable types.
Sample:
int a = int.Parse(textBox1.Text);
int b = int.Parse(textBox2.Text);
int c = Math.Max(a, b);
int d = Math.Min(a, b);
label1.Text = "The larger of the numbers is " + c.ToString() + ", the smaller is " + d.ToString() ;
Calculating Power of Number - Math.Pow Method
It is used to calculate the power of a number.
Used as Math.Pow (base, power).
Sample:
int a = int.Parse(textBox1.Text);
int b = int.Parse(textBox2.Text);
double result = Math.Pow( a, b);
label1.Text = result.ToString();
Calculating Square Root of Number - Math.Sqrt Method
We can calculate the square root of a number with the sqrt method. The result will be of type double.
Sample:
int number = int.Parse(textBox1.Text);
double square square = Math.Sqrt ( number );
c# mathematical methods, round number down, number up, round number to the nearest side, round, floor, ceiling, method, square root of number
EXERCISES
There are no examples related to this subject.
Read 821 times.