RingDotNetfor Ring

Rounding and the Math class

Rounding looks simple until a total is a cent wrong. This lesson uses the Math class for the two rounding modes, for the digits after the point, for Floor, Ceiling and Truncate, for limits with Clamp, powers and logarithms, and shows how the rounding rule changes the total of a bill.

What you will learn#

The tutorial Numbers, dates and times used the basic functions and the tutorial Money showed why money needs care. This lesson is about the rules of rounding.

Note

Ring shows a number with two decimals unless you change it with decimals(n). The program uses decimals(3) for the step with digits, so that the third decimal is visible.

The program#

samples/UsingDotNet/tutorials/ch03_rounding.ring
# rounding and the Math class - Round with its modes, Floor, Ceiling, Truncate, DivRem, Clamp, Sign and the rounding of money
load "dotnet.ring"

using {
	"System"
}

func main

	oMath = new Math()

	# 1. Round has a MODE for the numbers that are exactly in the middle (x.5). "ToEven" (the default of .NET, called banker's rounding) goes to
	#    the even neighbor, so that rounding many numbers does not push the total up; "AwayFromZero" is the rule taught at school.
	? "1. Round of x.5 with the two modes:"
	? "   " + padRight("value",8) + padRight("ToEven",9) + "AwayFromZero"
	for nValue in [ 0.5, 1.5, 2.5, 3.5, -0.5, -1.5, -2.5 ]
		nEven = oMath.Round([ :value = nValue, :mode = "ToEven" ])
		nAway = oMath.Round([ :value = nValue, :mode = "AwayFromZero" ])
		? "   " + padRight("" + nValue,8) + padRight("" + nEven,9) + nAway
	next

	# 2. Digits after the point: Round(value, digits). The modes work for the middle of the digit too: 0.125 is in the middle between 0.12 and 0.13.
	#    ToEven chooses 0.12 (the last digit 2 is even) and AwayFromZero chooses 0.13; 0.135 is in the middle between 0.13 and 0.14: ToEven
	#    chooses 0.14 (4 is even).
	? nl + "2. Round with digits:"
	decimals(3)                                         # Ring shows two decimals by default: show three for this step
	? "   Round(3.14159, 2)             = " + oMath.Round([ :value = 3.14159, :digits = 2 ])
	for nValue in [ 0.125, 0.135 ]
		nEven = oMath.Round([ :value = nValue, :digits = 2, :mode = "ToEven" ])
		nAway = oMath.Round([ :value = nValue, :digits = 2, :mode = "AwayFromZero" ])
		? "   Round(" + nValue + ", 2): ToEven " + nEven + ", AwayFromZero " + nAway
	next
	decimals(2)

	# 3. Floor, Ceiling and Truncate: three other ways to a whole number. They differ only for negative numbers.
	? nl + "3. Floor, Ceiling, Truncate:"
	? "   " + padRight("value",8) + padRight("Floor",7) + padRight("Ceiling",9) + "Truncate"
	for nValue in [ 2.7, 2.2, -2.2, -2.7 ]
		? "   " + padRight("" + nValue,8) + padRight("" + oMath.Floor(nValue),7) + padRight("" + oMath.Ceiling(nValue),9) + oMath.Truncate(nValue)
	next
	? "   Floor goes down, Ceiling goes up, Truncate cuts the decimals (toward zero)."

	# 4. Division with a remainder. Ring has the operator % for the remainder; the sign of the remainder follows the sign of the first number.
	? nl + "4. division with a remainder:"
	? "   17 / 5 = " + floor(17 / 5) + " remainder " + (17 % 5)
	? "   -17 / 5 = " + oMath.Truncate(-17 / 5) + " remainder " + (-17 % 5) + "  (the remainder has the sign of -17)"

	# 5. Limits: Clamp keeps a number between a minimum and a maximum, Sign gives -1, 0 or 1, Abs the size without the sign
	? nl + "5. Clamp, Sign, Abs:"
	for nValue in [ -5, 40, 250 ]
		? "   Clamp(" + padRight("" + nValue,4) + ", 0, 100) = " + oMath.Clamp(nValue,0,100)
	next
	? "   Sign(-8) = " + oMath.Sign(-8) + ", Sign(0) = " + oMath.Sign(0) + ", Sign(8) = " + oMath.Sign(8) + ", Abs(-8) = " + oMath.Abs(-8)

	# 6. Powers and roots: Pow, Sqrt, Cbrt, Log, Log10, Exp and the constants PI and E
	? nl + "6. powers and logarithms:"
	? "   Pow(2, 10) = " + oMath.Pow(2,10) + ", Sqrt(144) = " + oMath.Sqrt(144) + ", Cbrt(27) = " + oMath.Cbrt(27)
	? "   Log10(1000) = " + oMath.Log10(1000) + ", Log2(1024) = " + oMath.Log2(1024) + ", Log(E) = " + oMath.Log(2.718281828459045)

	# 7. Rounding money: the total of many prices should not be wrong by a cent. The same prices rounded in two ways give two totals.
	? nl + "7. ten items of 0.125 each (one eighth of a unit):"
	nEvenTotal = 0
	nAwayTotal = 0
	for i = 1 to 10
		nEvenTotal += oMath.Round([ :value = 0.125, :digits = 2, :mode = "ToEven" ])
		nAwayTotal += oMath.Round([ :value = 0.125, :digits = 2, :mode = "AwayFromZero" ])
	next
	? "   rounded to cents with ToEven:       " + nEvenTotal + "   (the exact total is 1.25)"
	? "   rounded to cents with AwayFromZero: " + nAwayTotal
	? "   A shop uses ONE rule everywhere and rounds only the final amount, or the amount of each line, as the law of the country says."

func padRight cText,nWidth

	return cText + copy(" ",nWidth - len(cText))
Output
1. Round of x.5 with the two modes:
   value   ToEven   AwayFromZero
   0.50    0        1
   1.50    2        2
   2.50    2        3
   3.50    4        4
   -0.50   0        -1
   -1.50   -2       -2
   -2.50   -2       -3

2. Round with digits:
   Round(3.14159, 2)             = 3.140
   Round(0.125, 2): ToEven 0.120, AwayFromZero 0.130
   Round(0.135, 2): ToEven 0.140, AwayFromZero 0.140

3. Floor, Ceiling, Truncate:
   value   Floor  Ceiling  Truncate
   2.70    2      3        2
   2.20    2      3        2
   -2.20   -3     -2       -2
   -2.70   -3     -2       -2
   Floor goes down, Ceiling goes up, Truncate cuts the decimals (toward zero).

4. division with a remainder:
   17 / 5 = 3 remainder 2
   -17 / 5 = -3 remainder -2  (the remainder has the sign of -17)

5. Clamp, Sign, Abs:
   Clamp(-5  , 0, 100) = 0
   Clamp(40  , 0, 100) = 40
   Clamp(250 , 0, 100) = 100
   Sign(-8) = -1, Sign(0) = 0, Sign(8) = 1, Abs(-8) = 8

6. powers and logarithms:
   Pow(2, 10) = 1024, Sqrt(144) = 12, Cbrt(27) = 3
   Log10(1000) = 3, Log2(1024) = 10, Log(E) = 1

7. ten items of 0.125 each (one eighth of a unit):
   rounded to cents with ToEven:       1.20   (the exact total is 1.25)
   rounded to cents with AwayFromZero: 1.30
   A shop uses ONE rule everywhere and rounds only the final amount, or the amount of each line, as the law of the country says.

How it works#

Two modes for the middle#

A number that is exactly in the middle between two whole numbers (2.5) must go one way. ToEven (the default of .NET, also called banker's rounding) goes to the neighbor that is even: 0.5 and 2.5 go down, 1.5 and 3.5 go up. Over many numbers the errors cancel, so the sum of the rounded numbers stays close to the real sum. AwayFromZero is the rule taught at school: 2.5 becomes 3 and -2.5 becomes -3. The mode is a text, written in the named values of the call: Round([ :value = 2.5, :mode = "AwayFromZero" ]).

Digits#

:digits = 2 rounds to hundredths. The middle of a digit follows the same modes: 0.125 is between 0.12 and 0.13, and ToEven chooses 0.12.

Floor, Ceiling, Truncate#

All three give a whole number and differ only for negative numbers: Floor goes down (-2.2 becomes -3), Ceiling goes up (-2.2 becomes -2) and Truncate cuts the decimals (-2.2 becomes -2). Ring has its own floor(); Math adds Ceiling and Truncate.

The remainder#

17 % 5 is 2. For a negative first number the remainder is negative too (-17 % 5 is -2), as in C# and Java. When you need a result that is never negative (the index of a circular list, for example) add the divisor and take the remainder again: ((n % m) + m) % m.

Limits#

Clamp(value, min, max) keeps a value inside a range: a volume from 0 to 100, a color part from 0 to 255. Sign gives -1, 0 or 1, and Abs the size without the sign.

Powers and logarithms#

Pow(2, 10) is 1024, Sqrt(144) is 12, Cbrt(27) is 3 (the cube root). Log10(1000) is 3, Log2(1024) is 10, and Log(x) is the natural logarithm. The constants are Math.PI and Math.E.

Rounding money#

Ten items of 0.125 cost 1.25. Each item rounded to cents with ToEven is 0.12, so the total is 1.20; with AwayFromZero each is 0.13 and the total is 1.30. The right answer depends on the rule that the shop (or the law of the country) uses, and it must be the same rule everywhere in the program: round each line, or round only the final amount, but never mix them. For exact amounts keep money in whole cents (125 for 1.25), as the tutorial Money does.

What you learned#

Exercises#

  1. Write roundToStep(value, step) that rounds to the nearest 0.05 (the smallest coin) and test it with 1.02 and 1.03.
  2. Write mod(n, m) that is never negative and use it for the days of a week.
  3. Add the prices 19.99, 5.49 and 0.5 rounded to cents with both modes.
  4. Print Log2 of the powers of two from 1 to 1024 in a table.

Next#

Big numbers

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.