RingDotNetfor Ring

Numbers, dates and times

Math functions, converting text to numbers without crashing, numbers of any size, random numbers, and the date and time classes DateTime and TimeSpan.

What you will learn#

The program#

samples/UsingDotNet/tutorials/ch01_numbers_dates.ring
# numbers, parsing, dates and times
load "dotnet.ring"

using {
	"System"
	"System.Numerics"
	"System.Globalization"
}

func main

	oMath = new Math()

	# Math: functions on numbers
	? "Round to 2 digits : " + oMath.Round([ :value = 3.14159, :digits = 2 ])
	? "Square root of 144: " + oMath.Sqrt(144)
	? "Power 2^10        : " + oMath.Pow(2,10)
	? "Absolute, floor   : " + oMath.Abs(-7.5) + ", " + oMath.Floor(7.9)
	? "Min and Max       : " + oMath.Min(4,9) + ", " + oMath.Max(4,9)

	# Converting text to numbers: TryParse never fails, it tells you whether it worked
	aResult = new Int32().TryParse("123")
	? "TryParse '123'    : worked=" + aResult[1] + " value=" + aResult[2]
	aResult = new Int32().TryParse("12x")
	? "TryParse '12x'    : worked=" + aResult[1]

	# Very big numbers: BigInteger has no limit
	oBig = new BigInteger()
	nFactorial = oBig.Parse("1")
	for nNumber = 2 to 30
		nFactorial = oBig.Multiply(nFactorial,nNumber)
	next
	? "30!               : " + nFactorial.ToString()

	# Random numbers
	oRandom = new Random(42)
	? "Random 1..6       : " + oRandom.@Next([ :minValue = 1, :maxValue = 7 ]) + " (the same every run: the seed is 42)"

	# Dates: DateTime is a struct with year, month, day, hour...
	oDate = new DateTime(2024,12,25).AddHours(18).AddMinutes(30)          # a date, then 18:30 on that day
	? "A date            : " + oDate.Format("dddd, dd MMMM yyyy HH:mm")
	? "Year, month, day  : " + oDate.Year + ", " + oDate.Month + ", " + oDate.Day
	? "Day of the week   : " + oDate.DayOfWeek

	# Dates are immutable: methods return a new date
	oLater = oDate.AddDays(10).AddHours(-3)
	? "10 days later     : " + oLater.Format("yyyy-MM-dd HH:mm")

	# TimeSpan: the difference between two dates
	oSpan = new DateTime(2025,1,1).Subtract(oDate)
	? "Until new year    : " + oSpan.Days + " days and " + oSpan.Hours + " hours"
	? "In total hours    : " + oSpan.TotalHours

	# Parsing dates from text
	oParsed = new DateTime(2000,1,1).Parse("2024-07-04")
	? "Parsed            : " + oParsed.Format("d MMMM yyyy")

	# Cultures format the same date differently
	? "US style          : " + oDate.Format([ :format = "D", :provider = new CultureInfo("en-US") ])
	? "German style      : " + oDate.Format([ :format = "D", :provider = new CultureInfo("de-DE") ])
Output
Round to 2 digits : 3.14
Square root of 144: 12
Power 2^10        : 1024
Absolute, floor   : 7.50, 7
Min and Max       : 4, 9
TryParse '123'    : worked=1 value=123
TryParse '12x'    : worked=0
30!               : 265252859812191058636308480000000
Random 1..6       : 5 (the same every run: the seed is 42)
A date            : Wednesday, 25 December 2024 18:30
Year, month, day  : 2024, 12, 25
Day of the week   : Wednesday
10 days later     : 2025-01-04 15:30
Until new year    : 6 days and 5 hours
In total hours    : 149.50
Parsed            : 4 July 2024
US style          : Wednesday, December 25, 2024
German style      : Mittwoch, 25. Dezember 2024

How it works#

Math#

Math is a class of static functions: Round, Sqrt, Pow, Abs, Floor, Min, Max. Round has several versions (round to a whole number, round to some digits), so the program uses named arguments: Round([ :value = 3.14159, :digits = 2 ]). The names come from the .NET documentation, and the order does not matter.

TryParse: no crash#

Int32.Parse("abc") raises an error. TryParse never does: it returns a list [worked, value]. A method that has an out parameter in C# returns its results as a list in Ring: first the return value (here true or false), then the out values.

Ring
aResult = new Int32().TryParse("123")
if aResult[1]
	? "the number is " + aResult[2]
ok

BigInteger#

A Ring number is a 64-bit floating point number: after about 15 digits it loses precision. BigInteger stores any size exactly. The program computes 30! = 265252859812191058636308480000000. Create one from text with Parse("1"), and do arithmetic with methods: Multiply(a,b), Add, Pow.

Random#

new Random(42) starts a random generator with a seed. The same seed always gives the same numbers, which is useful in tests. Pass NULL as the seed (new Random(NULL)) for numbers that change every run. @Next takes a minimum and a maximum (the maximum is not included, so 1 and 7 give a die). The @ is there because Next is a Ring keyword.

DateTime#

A DateTime has a year, month, day, hour, minute and second. Make a date from the year, month and day, and add the time to it:

Ring
oDate = new DateTime(2024,12,25)                         # year, month, day: midnight
oDate = new DateTime(2024,12,25).AddHours(18).AddMinutes(30)       # 18:30: a method returns a new date, so the calls can be chained

Properties: Year, Month, Day, DayOfWeek (a text like Wednesday). Dates never change: AddDays(10) returns a new date. That is why you can chain: oDate.AddDays(10).AddHours(-3).

Parse turns a text into a date. It is a static method, so the program calls it on a date that is made only to reach it (new DateTime(2000,1,1).Parse("2024-07-04")); the result is a new date. ParseExact takes the format as well.

TimeSpan#

The difference between two dates is a TimeSpan: Subtract gives it, and it has Days, Hours and TotalHours (the whole span in hours, with decimals).

Formats and cultures#

Format("dddd, dd MMMM yyyy HH:mm") formats a date with a pattern. Some letters: yyyy year, MM month number, MMMM month name, dd day, dddd weekday, HH hour (24), mm minute. A culture changes the language: Format([ :format = "D", :provider = new CultureInfo("de-DE") ]) writes the long date in German.

What you learned#

Exercises#

  1. Print how many days are left until the end of this year.
  2. Parse the text "15/03/2024" with ParseExact and a format of dd/MM/yyyy.
  3. Compute 100! with BigInteger and print how many digits it has.
  4. Throw a die 10 times with Random and count how many sixes you get.
  5. Print today's date in three cultures (en-US, fr-FR, ja-JP).

Next#

Collections and LINQ

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