Math round си шарп

Учимся округлять в 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 используется, когда округляемое значение находится ровно посередине между двумя вариантами. Принимает значение из следующего перечисления:

Обратите внимание, что по умолчанию mode == MidpointRounding.ToEven , поэтому Math.Round(1.5) == Math.Round(2.5) == 2 .

Math.Floor, Math.Ceiling, Math.Truncate

Сводная таблица

Сориентироваться в методах округления может помочь следующая табличка:

Округление проводится в соответствии со стандартом IEEE Standard 754, section 4.

Целочисленное деление и взятие по модулю

В C# есть два замечательных оператора над целыми числами: / для целочисленного деления (MSDN) и % для взятия остатка от деления (MSDN). Деление производится по следующим правилам:

  • При целочисленном делении результат всегда округляется по направлению к нулю.
  • При взятии остатка от деления должно выполняться следующее правило: x % y = x – (x / y) * y

Также можно пользоваться шпаргалкой:

string.Format

При форматировании чисел в виде строки можно пользоваться функцией string.Format (см. Standard Numeric Format Strings, Custom Numeric Format Strings). Например, для вывода числа с двумя знаками после десятичной точки можно воспользоваться string.Format(«», value) или string.Format(«», value) . Округление происходит по принципу AwayFromZero . Проиллюстрируем правила округления очередной табличкой:

Задачи

На приведённую тему есть две задачки в ProblemBook.NET: Rounding1, Rounding2.

Источник

C# Math.Round() – Syntax & Examples

In this tutorial, we will learn about the C# Math.Round() method, and learn how to use this method to round a given number to the nearest integral value, with the help of examples.

Читайте также:  Интерактивная карта css html

Round(Decimal)

Math.Round(d) rounds a decimal value d to the nearest integral value, and rounds midpoint values to the nearest even number.

Syntax

The syntax of Round(d) method is

Parameter Description
d The decimal number to be rounded.

Return Value

The method returns rounded Decimal value.

Example 1 – Round(d)

In this example, we will take some decimal values and round them to the nearest integral values using Math.Round() method.

using System; class Example < static void Main(string[] args) < Decimal d, result; d = 10.2563M; result = Math.Round(d); Console.WriteLine($"Round() = "); d = 10.63M; result = Math.Round(d); Console.WriteLine($"Round() = "); d = 10.5M; result = Math.Round(d); Console.WriteLine($"Round() = "); > >
Round(10.2563) = 10 Round(10.63) = 11 Round(10.5) = 10

Round(Decimal, Int32)

Math.Round(d, decimals) rounds a decimal value d to a specified number of fractional digits decimals , and rounds midpoint values to the nearest even number.

Syntax

The syntax of Round(d, decimals) method is

Math.Round(Decimal d, Int32 decimals)
Parameter Description
d The decimal number to be rounded.
decimals The number of decimal places in the return value.

Return Value

Example 2 – Round(d, decimals)

In this example, we will take some decimal values and round them to specific number of decimal points using Math.Round() method.

using System; class Example < static void Main(string[] args) < Decimal d, result; Int32 decimals; d = 10.2563M; decimals = 2; result = Math.Round(d, decimals); Console.WriteLine($"Round(, ) = "); d = 10.63524M; decimals = 1; result = Math.Round(d, decimals); Console.WriteLine($"Round(, ) = "); d = 10.5M; decimals = 0; result = Math.Round(d, decimals); Console.WriteLine($"Round(, ) = "); > >
Round(10.2563, 2) = 10.26 Round(10.63524, 1) = 10.6 Round(10.5, 0) = 10

Round(Decimal, Int32, MidpointRounding)

Math.Round(d, decimals, mode) rounds a decimal value d to a specified number of fractional digits decimals , and uses the specified rounding convention mode for midpoint values.

Syntax

The syntax of Round(d, decimals, MidpointRounding) method is

Math.Round(Decimal d, Int32 decimals, MidpointRounding mode)
Parameter Description
d The decimal number to be rounded.
decimals The number of decimal places in the return value.
mode Specification for how to round d if it is midway between two other numbers.

Return Value

The method returns rounded Decimal value.

Example 3 – Round(d, decimals, mode)

In this example, we will take some decimal values and round them to specific number of decimal points with different modes using Math.Round() method.

using System; class Example < static void Main(string[] args) < Decimal d, result; Int32 decimals; d = 10.2M; decimals = 0; result = Math.Round(d, decimals, MidpointRounding.AwayFromZero); Console.WriteLine($"Round(, , MidpointRounding.AwayFromZero) = "); d = 10.8M; decimals = 0; result = Math.Round(d, decimals, MidpointRounding.ToEven); Console.WriteLine($"Round(, , MidpointRounding.ToEven) = "); d = 10.8M; decimals = 0; result = Math.Round(d, decimals, MidpointRounding.ToNegativeInfinity); Console.WriteLine($"Round(, , MidpointRounding.ToNegativeInfinity) = "); d = 10.2M; decimals = 0; result = Math.Round(d, decimals, MidpointRounding.ToPositiveInfinity); Console.WriteLine($"Round(, , MidpointRounding.ToPositiveInfinity) = "); d = 10.8M; decimals = 0; result = Math.Round(d, decimals, MidpointRounding.ToZero); Console.WriteLine($"Round(, , MidpointRounding.ToZero) = "); > >
Round(10.2, 0, MidpointRounding.AwayFromZero) = 10 Round(10.8, 0, MidpointRounding.ToEven) = 11 Round(10.8, 0, MidpointRounding.ToNegativeInfinity) = 10 Round(10.2, 0, MidpointRounding.ToPositiveInfinity) = 11 Round(10.8, 0, MidpointRounding.ToZero) = 10

Round(Decimal, MidpointRounding)

Math.Round(d, mode) rounds a decimal value d to the nearest integer, and uses the specified rounding convention mode for midpoint values.

Читайте также:  Python read json lines file

Syntax

The syntax of Round(d, mode) method is

Math.Round(Decimal d, MidpointRounding mode)
Parameter Description
d The decimal number to be rounded.
mode Specification for how to round the value d if it is midway between two other numbers.

Return Value

The method returns rounded Decimal value.

Example 4 – Round(Decimal, MidpointRounding)

In this example, we will take some decimal values and round them with different modes using Math.Round() method.

using System; class Example < static void Main(string[] args) < Decimal d, result; d = 10.2M; result = Math.Round(d, MidpointRounding.AwayFromZero); Console.WriteLine($"Round(, MidpointRounding.AwayFromZero) = "); d = 10.8M; result = Math.Round(d, MidpointRounding.ToEven); Console.WriteLine($"Round(, MidpointRounding.ToEven) = "); d = 10.8M; result = Math.Round(d, MidpointRounding.ToNegativeInfinity); Console.WriteLine($"Round(, MidpointRounding.ToNegativeInfinity) = "); d = 10.2M; result = Math.Round(d, MidpointRounding.ToPositiveInfinity); Console.WriteLine($"Round(, MidpointRounding.ToPositiveInfinity) = "); d = 10.8M; result = Math.Round(d, MidpointRounding.ToZero); Console.WriteLine($"Round(, MidpointRounding.ToZero) = "); > >
Round(10.2, MidpointRounding.AwayFromZero) = 10 Round(10.8, MidpointRounding.ToEven) = 11 Round(10.8, MidpointRounding.ToNegativeInfinity) = 10 Round(10.2, MidpointRounding.ToPositiveInfinity) = 11 Round(10.8, MidpointRounding.ToZero) = 10

Round(Double)

Math.Round(d) rounds a double-precision floating-point value d to the nearest integral value, and rounds midpoint values to the nearest even number.

Syntax

The syntax of Round(d) method is

Parameter Description
d The double-precision floating-point number to be rounded.

Return Value

The method returns rounded Double value.

Example 5 – Round(d)

In this example, we will take some double-precision floating-point numbers and round them to the nearest integral values using Math.Round() method.

using System; class Example < static void Main(string[] args) < Double d, result; d = 10.2563; result = Math.Round(d); Console.WriteLine($"Round() = "); d = 10.63; result = Math.Round(d); Console.WriteLine($"Round() = "); d = 10.5; result = Math.Round(d); Console.WriteLine($"Round() = "); > >
Round(10.2563) = 10 Round(10.63) = 11 Round(10.5) = 10

Round(Double, Int32)

Math.Round(d, decimals) rounds a double-precision floating-point value d to a specified number of fractional digits decimals , and rounds midpoint values to the nearest even number.

Syntax

The syntax of Round(d, decimals) method is

Math.Round(Double d, Int32 decimals)
Parameter Description
d The double-precision floating-point number to be rounded.
decimals The number of decimal places in the return value.

Return Value

The method returns rounded Double value.

Example 6 – Round(Double, Int32)

In this example, we will take some decimal double-precision floating-point numbers and round them to specific number of decimal points using Math.Round() method.

using System; class Example < static void Main(string[] args) < Double d, result; Int32 decimals; d = 10.2563; decimals = 2; result = Math.Round(d, decimals); Console.WriteLine($"Round(, ) = "); d = 10.63524; decimals = 1; result = Math.Round(d, decimals); Console.WriteLine($"Round(, ) = "); d = 10.5; decimals = 0; result = Math.Round(d, decimals); Console.WriteLine($"Round(, ) = "); > >
Round(10.2563, 2) = 10.26 Round(10.63524, 1) = 10.6 Round(10.5, 0) = 10

Round(Double, Int32, MidpointRounding)

Math.Round(d, decimals, mode) rounds a double-precision floating-point value d to a specified number of fractional digits decimals , and uses the specified rounding convention mode for midpoint values.

Читайте также:  Sending mail smtp python

Syntax

The syntax of Round(d, decimals, mode) method is

Math.Round(Double d, Int32 decimals, MidpointRounding mode)
Parameter Description
d The double-precision floating-point number to be rounded.
decimals The number of decimal places in the return value.
mode Specification for how to round d if it is midway between two other numbers.

Return Value

The method returns rounded Double value.

Example 7 – Round(Double, Int32, MidpointRounding)

In this example, we will take some decimal double-precision floating-point numbers and round them to specific number of decimal points with different modes using Math.Round() method.

using System; class Example < static void Main(string[] args) < Double d, result; Int32 decimals; d = 10.2; decimals = 0; result = Math.Round(d, decimals, MidpointRounding.AwayFromZero); Console.WriteLine($"Round(, , MidpointRounding.AwayFromZero) = "); d = 10.8; decimals = 0; result = Math.Round(d, decimals, MidpointRounding.ToEven); Console.WriteLine($"Round(, , MidpointRounding.ToEven) = "); d = 10.8; decimals = 0; result = Math.Round(d, decimals, MidpointRounding.ToNegativeInfinity); Console.WriteLine($"Round(, , MidpointRounding.ToNegativeInfinity) = "); d = 10.2; decimals = 0; result = Math.Round(d, decimals, MidpointRounding.ToPositiveInfinity); Console.WriteLine($"Round(, , MidpointRounding.ToPositiveInfinity) = "); d = 10.8; decimals = 0; result = Math.Round(d, decimals, MidpointRounding.ToZero); Console.WriteLine($"Round(, , MidpointRounding.ToZero) = "); > >
Round(10.2, 0, MidpointRounding.AwayFromZero) = 10 Round(10.8, 0, MidpointRounding.ToEven) = 11 Round(10.8, 0, MidpointRounding.ToNegativeInfinity) = 10 Round(10.2, 0, MidpointRounding.ToPositiveInfinity) = 11 Round(10.8, 0, MidpointRounding.ToZero) = 10

Round(Double, MidpointRounding)

Math.Round(d, mode) rounds a double-precision floating-point value d to the nearest integer, and uses the specified rounding convention mode for midpoint values.

Syntax

The syntax of Round(d, mode) method is

Math.Round(Double d, MidpointRounding mode)
Parameter Description
d The double-precision floating-point number to be rounded.
mode Specification for how to round the value d if it is midway between two other numbers.

Return Value

The method returns rounded Double value.

Example 8 – Round(Double, MidpointRounding)

In this example, we will take some double-precision floating-point numbers and round them with different modes using Math.Round() method.

using System; class Example < static void Main(string[] args) < Double d, result; d = 10.2; result = Math.Round(d, MidpointRounding.AwayFromZero); Console.WriteLine($"Round(, MidpointRounding.AwayFromZero) = "); d = 10.8; result = Math.Round(d, MidpointRounding.ToEven); Console.WriteLine($"Round(, MidpointRounding.ToEven) = "); d = 10.8; result = Math.Round(d, MidpointRounding.ToNegativeInfinity); Console.WriteLine($"Round(, MidpointRounding.ToNegativeInfinity) = "); d = 10.2; result = Math.Round(d, MidpointRounding.ToPositiveInfinity); Console.WriteLine($"Round(, MidpointRounding.ToPositiveInfinity) = "); d = 10.8; result = Math.Round(d, MidpointRounding.ToZero); Console.WriteLine($"Round(, MidpointRounding.ToZero) = "); > >
Round(10.2, MidpointRounding.AwayFromZero) = 10 Round(10.8, MidpointRounding.ToEven) = 11 Round(10.8, MidpointRounding.ToNegativeInfinity) = 10 Round(10.2, MidpointRounding.ToPositiveInfinity) = 11 Round(10.8, MidpointRounding.ToZero) = 10

Conclusion

In this C# Tutorial, we have learnt the syntax of C# Math.Round() method, and also learnt how to use this method with the help of examples.

Источник

Оцените статью