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#
Mathfor rounding, roots and powers,TryParse: turn text into a number safely,BigInteger: numbers without a limit,Random,DateTime,TimeSpan, parsing dates and formatting in different cultures.
The program#
# 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") ])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 2024How 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.
aResult = new Int32().TryParse("123")
if aResult[1]
? "the number is " + aResult[2]
okBigInteger#
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:
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 chainedProperties: 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#
Mathfunctions and named arguments,TryParsefor safe conversion,BigIntegerfor exact big numbers,- dates are values that you copy, never change,
- format patterns and cultures.
Exercises#
- Print how many days are left until the end of this year.
- Parse the text
"15/03/2024"withParseExactand a format ofdd/MM/yyyy. - Compute 100! with
BigIntegerand print how many digits it has. - Throw a die 10 times with
Randomand count how many sixes you get. - Print today's date in three cultures (
en-US,fr-FR,ja-JP).