RingDotNetfor Ring

Formatting numbers and dates

The same number can be written as 1234.5678, 1,234.57, 123,456.8 % or 4D2. A format string says which. This lesson uses String.Format and the format methods for fixed decimals, thousands separators, percent, custom patterns, alignment in tables, dates and durations.

What you will learn#

The tutorial Cultures shows that the same format gives different texts in different countries. This lesson is about the formats themselves.

The program#

samples/UsingDotNet/tutorials/ch02_formatting.ring
# formatting numbers and dates - format strings: fixed decimals, thousands, percent, hexadecimal, padding, alignment and custom patterns
load "dotnet.ring"

using {
	"System"
	"System.Globalization"
}

oString = new String()
oInvariant = ""

func main

	# A format string says HOW a value is written. The invariant culture is used here, so that the output is the same on every computer;
	# a program for people uses the culture of the user (the tutorial about cultures).
	oInvariant = new CultureInfo("en-US").InvariantCulture

	# 1. Standard formats for numbers: one letter, and often a number of digits after it. They are written in a placeholder {0:...} of
	#    String.Format; {0} means the first value.
	? "1. standard numeric formats for 1234.5678:"
	for cFormat in [ "F0", "F2", "N0", "N2", "E3", "P1", "C", "G" ]
		? "   {0:" + padRight(cFormat + "}",6) + one("{0:" + cFormat + "}",1234.5678)
	next
	? "   F = fixed decimals, N = with thousands separators, E = scientific, P = percent (the value is multiplied by 100),"
	? "   C = money (the invariant culture has no money symbol and shows the sign of an unknown currency; a country culture shows its own),"
	? "   G = general (the shortest form)"
	? "   {0:P1} of 0.256 = " + one("{0:P1}",0.256)

	# 2. Whole numbers. The formats D (zeros in front) and X (hexadecimal) are made for whole-number TYPES: a whole number that goes to
	#    String.Format is an Int32, so they work. Convert.ToString(number, base) writes a whole number in base 2, 8, 10 or 16 as well.
	? nl + "2. whole numbers, 255:"
	? "   base 16: " + toBase(255,16) + ", base 2: " + toBase(255,2) + ", base 8: " + toBase(255,8)
	? "   zeros in front, {0:D6}:        " + one("{0:D6}",255)
	? "   hexadecimal, {0:X} and {0:x4}:  " + one("{0:X}",255) + " and " + one("{0:x4}",255)
	? "   thousands separators:          " + one("{0:N0}",1234567)

	# 3. Custom patterns: you draw the number. 0 = a digit (a zero if there is none), # = a digit (nothing if there is none),
	#    , = thousands, . = decimals, % = percent
	? nl + "3. custom patterns:"
	for aItem in [ ["0.00",3.14159,"3.14159"], ["000.0",3.14159,"3.14159"], ["#,##0.00",1234567.891,"1234567.891"], ["#.##",0.5,"0.5"], ["#.##",12,"12"], ["0.0%",0.256,"0.256"], ["0 'kg'",72,"72"] ]
		? "   " + padRight(aItem[1],10) + one("{0:" + aItem[1] + "}",aItem[2]) + "     (for " + aItem[3] + ")"
	next

	# 4. Alignment: {0,10} gives the value 10 places, to the right; {0,-10} to the left. Columns of a table.
	? nl + "4. a table with alignment (names to the left, numbers to the right):"
	aPrices = [ ["Tea",2.5], ["Coffee",13.25], ["Orange juice",104] ]
	for aItem in aPrices
		? "   " + oString.Format([ :provider = oInvariant, :format = "|{0,-14}|{1,9:F2}|", :arg0 = aItem[1], :arg1 = aItem[2] ])
	next

	# 5. Dates: the letters mean year (yyyy), month (MM), day (dd), hour (HH), minute (mm), second (ss), month name (MMMM, MMM) and the
	#    day of the week (dddd). A standard letter is a ready-made pattern: d short date, D long date, t short time, o round trip.
	oDate = (new DateTime).@New([ :year = 2030, :month = 3, :day = 9, :hour = 14, :minute = 5, :second = 7 ])
	? nl + "5. dates (2030-03-09 14:05:07):"
	for cPattern in [ "yyyy-MM-dd", "dd/MM/yyyy", "d MMMM yyyy", "dddd", "MMM d, yyyy", "HH:mm:ss", "h:mm tt", "yyyyMMdd_HHmmss", "d", "D", "t", "o" ]
		? "   " + padRight(cPattern,18) + oDate.Format([ :format = cPattern, :provider = oInvariant ])
	next

	# 6. Time spans have their own patterns: hours, minutes and seconds of a duration
	oSpan = new TimeSpan().FromSeconds(3725)
	? nl + "6. a duration of 3725 seconds:"
	? "   hh\:mm\:ss = " + oSpan.Format([ :format = "hh\:mm\:ss", :formatProvider = oInvariant ])
	? "   h 'h' m 'min' = " + oSpan.Format([ :format = "h' h 'm' min'", :formatProvider = oInvariant ])

	# 7. A pattern that does not fit the value raises an error, which is better than a wrong text: the letter Z is not a number format
	try
		? one("{0:Z}",12)
	catch
		? nl + "7. a wrong format: " + errorKind(cCatchError)
	done

# a whole number in another base (a static method of Convert)
func toBase nNumber,nBase

	return (new Convert).Format([ :value = nNumber, :toBase = nBase ])

# format one value with the invariant culture
func one cFormat,value

	return oString.Format([ :provider = oInvariant, :format = cFormat, :arg0 = value ])

func padRight cText,nWidth

	return "" + cText + copy(" ",nWidth - len("" + cText))

func errorKind cMessage

	cText = trim(cMessage)
	nStart = substr(cText,"DotNet Error: ")
	if nStart > 0
		cText = substr(cText,nStart + 14)
	ok
	nEnd = substr(cText,":")
	if nEnd > 0
		cText = left(cText,nEnd - 1)
	ok
	return cText
Output
1. standard numeric formats for 1234.5678:
   {0:F0}   1235
   {0:F2}   1234.57
   {0:N0}   1,235
   {0:N2}   1,234.57
   {0:E3}   1.235E+003
   {0:P1}   123,456.8 %
   {0:C}    ¤1,234.57
   {0:G}    1234.5678
   F = fixed decimals, N = with thousands separators, E = scientific, P = percent (the value is multiplied by 100),
   C = money (the invariant culture has no money symbol and shows the sign of an unknown currency; a country culture shows its own),
   G = general (the shortest form)
   {0:P1} of 0.256 = 25.6 %

2. whole numbers, 255:
   base 16: ff, base 2: 11111111, base 8: 377
   zeros in front, {0:D6}:        000255
   hexadecimal, {0:X} and {0:x4}:  FF and 00ff
   thousands separators:          1,234,567

3. custom patterns:
   0.00      3.14     (for 3.14159)
   000.0     003.1     (for 3.14159)
   #,##0.00  1,234,567.89     (for 1234567.891)
   #.##      .5     (for 0.5)
   #.##      12     (for 12)
   0.0%      25.6%     (for 0.256)
   0 'kg'    72 kg     (for 72)

4. a table with alignment (names to the left, numbers to the right):
   |Tea           |     2.50|
   |Coffee        |    13.25|
   |Orange juice  |   104.00|

5. dates (2030-03-09 14:05:07):
   yyyy-MM-dd        2030-03-09
   dd/MM/yyyy        09/03/2030
   d MMMM yyyy       9 March 2030
   dddd              Saturday
   MMM d, yyyy       Mar 9, 2030
   HH:mm:ss          14:05:07
   h:mm tt           2:05 PM
   yyyyMMdd_HHmmss   20300309_140507
   d                 03/09/2030
   D                 Saturday, 09 March 2030
   t                 14:05
   o                 2030-03-09T14:05:07.0000000

6. a duration of 3725 seconds:
   hh\:mm\:ss = 01:02:05
   h 'h' m 'min' = 1 h 2 min

7. a wrong format: System.FormatException
Note

This program uses a few generic functions (dnNew, dnStatic) where a class cannot be used. The lesson The generic functions explains them.

How it works#

The invariant culture#

Decimal separators, thousands separators, month names and money symbols depend on the culture. The program passes new CultureInfo("en-US").InvariantCulture to every call, so the output is the same on every computer. For text that goes to a file or to another program (data) use the invariant culture. For text that a person reads use the culture of that person, which is the default when you leave the provider out.

Placeholders#

String.Format takes a text with placeholders: {0} is the first value, {1} the second. After a colon comes the format of that value: {0:N2}. In Ring the values are named :arg0, :arg1 and so on, and the text is :format: oString.Format([ :provider = oCulture, :format = "{0:N2}", :arg0 = 1234.5678 ]).

Standard number formats#

One letter, and often a number of digits. F is fixed: F2 always has two decimals. N is the same with thousands separators. E is scientific. P is a percent: the value is multiplied by 100 (0.256 is 25.6 %). C is money. G is the shortest general form. The number after the letter means decimals for F, N, P and C.

Whole numbers#

The formats D (zeros in front) and X (hexadecimal) are made for whole-number types, and a whole number that goes to String.Format is an Int32, so {0:D6} gives 000255 and {0:X} gives FF (a number with a fraction is a Double, which those two formats refuse). Convert.ToString(255, 16) gives ff (bases 2, 8, 10 and 16 work). Convert.ToString is called with dnStatic because ToString is also a method of every object.

Custom patterns#

A custom pattern draws the number: 0 is a digit that is always written (a zero if there is none), # is a digit that is written only when there is one, , is the thousands separator, . the decimal point and % multiplies by 100 and adds the sign. 000.0 gives 003.1; #.## gives .5 for 0.5 and 12 for 12, with no zeros. Text in single quotes is written as it is (0 'kg').

Alignment#

{0,-14} writes the value in 14 places, to the left; {1,9:F2} writes the second value in 9 places to the right, with two decimals. A table of prices lines up on the decimal point because every number has the same width and the same decimals. (In Ring programs that only print, padRight functions do the same; here the format does it in one text.)

Dates and durations#

The letters of a date pattern are the same everywhere: yyyy year, MM month number, MMMM month name, dd day, dddd day name, HH hours (24), h and tt hours (12) and AM/PM, mm minutes, ss seconds. A single letter is a ready-made pattern: d short date, D long date, t short time, o the round trip form that always reads back to the same moment (use it in files). The : and / in a pattern mean the separators of the culture. A TimeSpan has its own patterns: hh\:mm\:ss (the backslash says that the colon is just a colon) and h' h 'm' min'.

A wrong pattern#

A letter that is not a format raises System.FormatException, not a wrong text. The program catches it and prints the kind of the error.

What you learned#

Exercises#

  1. Print the numbers 1 to 5 and their squares in two columns, with the squares aligned to the right.
  2. Write money(value) that always gives two decimals and thousands separators.
  3. Write the date of today in the forms 2030-03-09, 9 Mar 2030 and Saturday 9 March.
  4. Show a duration of 90061 seconds as 1 d 01:01:01 (the pattern d' d 'hh\:mm\:ss).

Next#

Unicode and encodings

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