Rounding double values in C#
I want a rounding method on double values in C#. It needs to be able to round a double value to any rounding precision value. My code on hand looks like:
So RoundI(100, 3) should give 99 and RoundI(1.2345, 0.001) should give 1.235.
The problem is, RoundI(1.275, 0.01) returns 1.27, rather than 1.28. This is because when executing double valIntvRatio = val/intv, that is, double valIntvRatio = 1.275 / 0.01, it gives 0.12749999999999. I know this is a problem with double representation in any programming language. My question is, is there a standard code to do things like this, without the need to worry about precision on double? Here I set the tolerant to 1e-14, but this is too restrict for this problem and I don’t know what is the correct tolerance to be set. Thank you for any help.
C round() Function
In C programming language, there are many mathematical functions used for fast calculations, and also they are very simple to use. One of these functions is the C round() function and it is present inside the <math.h> module of the C Library. The basic intuition of using the C round() functions is that it easily converts a number to its nearest integer value (which may be small or large).
What is C round() Function?
The C round() function is one of the mathematical functions which is found in <math.h> module of the C library. The round() function in C returns the nearest integer value (rounded value) of the given float, integer, or double number based on the decimal part of the number. If the decimal value of the number provided is less than or equal to 0.5 , then the value returned will be the integer smaller than the number provided in the argument, and if the decimal value of the number provided is greater than 0.5 , then the value returned will be the integer greater than the number provided in the argument. The integer returned by the round() function will be proper and it will not contain any decimal part.
Syntax of C round() Function
The syntax of the round function is very simple, it just accepts one argument which can be float, int, or double, and it returns the integer by rounding it off to the accurate value. Its generic syntax is as follows
Here the num variable can be of float, or double type and the roundedValue will be an integer returned by the round() function and the roundedValue will not contain any decimal part.
Parameters of C round() Function
The C round function accepts only one value which can be passed as a parameter. The parameter of the C round function is a real number and it can be of the form float, integer, double or long double. If the user provides a variable of any other data type, then a compiler error will occur in the code because this function can accept only numbers as an argument.
Return Value of C round() Function
The round() function in C returns the nearest integer value (rounded off value) of the number provided as an argument which can be of type float, integer, or double number provided as an argument. If the decimal value of the number provided is less than or equal to 0.5 , then the value returned will be the integer smaller than the number provided in the argument, and if the decimal value of the number provided is greater than 0.5 , then the value returned will be the integer greater than the number provided in the argument.
How does the round() Function in C work?
The round() function in C works in a very easy and simple way. The first step we have to follow is that we have to include the <math.h> library in C. Then we are good to start with the round() function. The round function accepts an argument that can be of any type from int, float, double or long double. It returns the closest integer value to that number. In the case of negative numbers, it will first convert the number into positive, and then it will apply the above logic to find the nearest integer to that number, and finally, it will again convert that integer to a negative integer and return a negative integer.
Below shown is the image of the numbers and their rounded-off values.
Requesting graphic team to create a similar image
Uses of round() Function in C
The round function is one of the most used mathematical functions in the field of algebra, geometry, and many other areas of mathematics. It is mainly used to show the approximation of the decimal values, for example, finding the approximate value of the temperature, finding the estimated bank balance, the rating of movies or songs, etc. As it finds the nearest integer of the given number, it is also used widely in computational problems, Statistics, Machine Learning, Artificial Intelligence, etc.
C round() Function Examples
The C round() function can take the int, float, and double value as an argument and returns the nearest integer to that value after rounding it off. Below is an example of all types of arguments.
Example 1
Output
In the above case, the argument passed is a float number. The output, in this case, will be a smaller integer than this number because the decimal value is 0.014 , which is less than 0.5 , and as we have discussed above that if the decimal value will be less than or equal to 0.5 , the round() function will return the smaller integer than this number. So the output, in this case, will be 7` because it is a smaller integer than the given float number.
Example 2
Output
In the above case, the argument passed is a float number. The output, in this case, will be a smaller integer than this number because the decimal value is 0.4 , which is less than 0.5 , and as we have discussed above that if the decimal value will be less than or equal to 0.5 , the round() function will return the smaller integer than this number. So the output, in this case, will be 2 because it is a smaller integer than the given float number.
Example 3
Output
In the above case, the argument passed is a float number. The output, in this case, will be the greater integer than this number because the decimal value is 0.65 , which is greater than 0.5 , and as we have discussed above that if the decimal value will be greater than or equal to 0.5 , the round() function will return the greater integer than this number with the precession of 0 because the value returned by the round() function does not contain any decimal value. So the output, in this case, will be 4 because it is a greater integer than the given float number.
Example 4
Output
In the above case, the argument passed is a double number. The output, in this case, will be a smaller integer than this number because the decimal value is 0.2325467 which is less than 0.5 , and as we have discussed above that if the decimal value will be less than or equal to 0.5 , the round() function will return the smaller integer than this number. So the output, in this case, will be 8 because it is a smaller integer than the given float number.
Example 5
Output
In the above case, the argument passed is a double number. The output, in this case, will be the greater integer than this number because the decimal value is 0.7390878 which is greater than 0.5 , although as we have discussed above that if the decimal value will be greater than or equal to 0.5 , the round() function will return the greater integer than this number with the precision of 0 because the value returned by the round() function does not contain any decimal value, and as it is the negative value case, it will return the opposite, this means it first converts the negative value to the positive value and then returns the integer value. So the output, in this case, will be -6 because it is a greater integer than the given float number.
Conclusion
In this quick tutorial, we have learned about the C round() function which is widely used in mathematics for fast and efficient calculation, and we have discussed the following
Учимся округлять в C#
А знаете ли вы, что Math.Round(1.5) == Math.Round(2.5) == 2 ? Можете ли сходу сказать, сколько будет -7%3 и 7%-3 ? Помните ли, чем отличаются Math.Round , Math.Floor , Math.Ceiling , Math.Truncate ? А как происходит округление при использовании string.Format ? Давайте немного погрузимся в мир округлений и разберёмся с нюансами, которые не для всех могут быть очевидными.
Math.Round
Math.Round — это метод округления к ближайшему числу или к ближайшему числу с заданным количеством знаков после запятой. Работает с типами decimal и double , в параметрах можно встретить три вида параметров:
- value : округляемое число
- digits : количество знаков в дробной части, которые нужно оставить
- mode : параметр, который определяет в какую сторону округлять число, которое находится ровно посередине между двумя вариантами
Параметр mode используется, когда округляемое значение находится ровно посередине между двумя вариантами. Принимает значение из следующего перечисления:
- AwayFromZero : округление происходит к тому числу, которое дальше от нуля.
- ToEven : округление происходит к чётному числу.
Обратите внимание, что по умолчанию mode == MidpointRounding.ToEven , поэтому Math.Round(1.5) == Math.Round(2.5) == 2 .
Math.Floor, Math.Ceiling, Math.Truncate
- Math.Floor округляет вниз по направлению к отрицательной бесконечности.
- Math.Ceiling округляет вверх по направлению к положительной бесконечности.
- Math.Truncate округляет вниз или вверх по направлению к нулю.
Сводная таблица
Сориентироваться в методах округления может помочь следующая табличка:
Округление проводится в соответствии со стандартом IEEE Standard 754, section 4.
Целочисленное деление и взятие по модулю
В C# есть два замечательных оператора над целыми числами: / для целочисленного деления (MSDN) и % для взятия остатка от деления (MSDN). Деление производится по следующим правилам:
C# | Math.Round() Method | Set – 1
In C#, Math.Round() is a Math class method which is used to round a value to the nearest integer or to the particular number of fractional digits. This method can be overloaded by changing the number and type of the arguments passed. There are total 8 methods in the overload list of the Math.Round() method. Here we will discuss only 4 methods and remaining 4 methods are discussed in C# | Math.Round() Method | Set – 2.
- Math.Round(Double)
- Math.Round(Double, Int32)
- Math.Round(Decimal)
- Math.Round(Decimal, Int32)
Math.Round(Double)
This method rounds a double-precision floating-point value to the nearest integer value.
x: A double floating-point number which is to be rounded. Type of this parameter is System.Double.
Return Type:It returns the integer nearest to x and return type is System.Double.
Note: In case if the fractional component of x is halfway between two integers, one of which is even and the other odd, then the even number is returned.
Example:
Explanation: In above code suppose the user wants to round off the above specified double value to nearest integer. So the compiler will first check whether that double value is greater than or less than the even and odd integral value of that double number. If it is less than the halfway value, its output will be floor value, else if greater than halfway value, its output will be the ceiling value.
Math.Round(Double, Int32)
This method rounds a double precision floating-point value to a specified number of fractional digits.
x: A double floating-point number which is to be rounded. Type of this parameter is System.Double.
y: It is the number of fractional digits in the returned value. Type of this parameter is System.Int32.
Return Type:It returns the integer nearest to x which contains a number of fractional digits equal to y and return type is System.Double.
Exception: This method will give ArgumentOutOfRangeException if the value of y is less than 0 or greater than 15.
Example:
Explanation: Method will check that whether the digit next to the specified number of decimal digits is greater than or equals to 5 or not. If it is greater than or equal to 5 then it increments the previous number else previous digit remains the same.
Math.Round(Decimal)
This method rounds off a decimal value whose precision is 128 bits to the nearest integer value.
x: It is decimal number which is to be rounded. Type of this parameter is System.Decimal.
Return Type:It returns the integer nearest to x and return type is System.Decimal.
Note: In case if the fractional component of x is halfway between two integers, one of which is even and the other odd, then the even number is returned.
Example:
Math.Round(Decimal, Int32)
This method rounds a decimal value to a specified number of fractional digits.
x: A decimal number which is to be rounded. Type of this parameter is System.Decimal.
y: It is the number of fractional digits in the returned value. Type of this parameter is System.Int32.
Return Type:It returns the integer nearest to x which contains a number of fractional digits equal to y and return type is System.Decimal.
Exception: This method will give ArgumentOutOfRangeException if the value of y is less than 0 or greater than 15 and OverflowException in case of result is outside the range of a Decimal.