ZetCode

Scheme number formatting

last modified November 25, 2026 Guile 3.0

display prints a number in its shortest form, which is not always the form a reader wants. Reports need a fixed number of decimal places, numbers aligned in columns, thousands separators, or leading zeros. The format procedure from the (ice-9 format) module does all of this with directives that take parameters. The ports and output article introduces format and its ~a, ~s, ~d, and list directives; this article covers the numeric directives in GNU Guile 3.0.7. The numbers article covers number->string and number literals.

Integers in a field

Parameters are written between the tilde and the directive letter. The first parameter of ~d is the minimum width of the field; the number is aligned to the right. The second parameter is the padding character, written with a quote before it.

widths.scm
(use-modules (ice-9 format))

(format #t "[~d]~%" 42)
(format #t "[~5d]~%" 42)
(format #t "[~5d]~%" -42)
(format #t "[~5,'0d]~%" 42)
(format #t "[~@d] [~@d]~%" 42 -42)
(format #t "[~3d]~%" 123456)

(for-each (lambda (n)
            (format #t "~3d. ~5d~%" n (* n n n)))
          '(1 5 12 40))

~5d pads 42 with spaces to five characters, and the minus sign of -42 counts towards the width. ~5,'0d pads with zeros. The @ modifier always prints the sign. The width is a minimum, so a number that needs more space is printed in full rather than cut. Fixed widths line up the numbers in the small table of cubes. ~d accepts only integers; 3.5 makes format fail with argument not an integer.

$ guile widths.scm
[42]
[   42]
[  -42]
[00042]
[+42] [-42]
[123456]
  1.     1
  5.   125
 12.  1728
 40. 64000

Grouping digits

The : modifier separates groups of digits. The third parameter of ~d is the separator, and the fourth the size of a group, so the first two parameters are left empty when only those are needed.

grouping.scm
(use-modules (ice-9 format))

(define (factorial n)
  (if (= n 0) 1 (* n (factorial (- n 1)))))

(format #t "~:d~%" 1234567)
(format #t "~:d~%" -9876543210)
(format #t "~,,' ,3:d~%" 1234567)
(format #t "~,,'.,3:d~%" 1234567)
(format #t "~,,'_,4:d~%" 12345678)
(format #t "~12:d~%" 1234567)
(format #t "~@:d~%" 1000)
(format #t "25! = ~:d~%" (factorial 25))

~:d uses commas and groups of three. ~,,' ,3:d uses a space, as is common in Slovakia and France, and ~,,'.,3:d a dot, as in Germany. The separators count towards the width in ~12:d. Modifiers can be combined: ~@:d prints the sign and the separators. Grouping helps most with big integers such as 25!, which Scheme computes exactly.

$ guile grouping.scm
1,234,567
-9,876,543,210
1 234 567
1.234.567
1234_5678
   1,234,567
+1,000
25! = 15,511,210,043,330,985,984,000,000

Other bases

number->string converts a number to a string in a base from 2 to 36. format has ~x, ~o, and ~b for hexadecimal, octal, and binary, which take the same parameters as ~d, and ~r with the base as its first parameter.

bases.scm
(use-modules (ice-9 format))

(display (number->string 200 2))
(newline)
(display (string-pad (number->string 5 2) 8 #\0))
(newline)

(format #t "~x ~o ~b~%" 200 200 200)
(format #t "~:@(~x~)~%" 48879)
(format #t "~8,'0b~%" 5)
(format #t "~,,'_,4:b~%" 48879)
(format #t "~3r ~7r ~36r~%" 100 100 100)
(format #t "#~2,'0x~2,'0x~2,'0x~%" 255 136 0)

(format #t "  dec  hex  oct      bin~%")
(for-each (lambda (n)
            (format #t "~5d ~4x ~4o ~8,'0b~%" n n n n))
          '(0 7 10 64 255))

number->string has no width, so the first part pads its result with string-pad to get eight binary digits. ~x writes lowercase digits; the case conversion ~:@(...~) from the ports article turns them to upper case. ~,,'_,4:b groups binary digits by four, which makes long patterns readable. ~3r, ~7r, and ~36r write 100 in bases 3, 7, and 36. Three ~2,'0x directives build an HTML colour, and the table shows the same numbers in four bases.

$ guile bases.scm
11001000
00000101
c8 310 11001000
BEEF
00000101
1011_1110_1110_1111
10201 202 2s
#ff8800
  dec  hex  oct      bin
    0    0    0 00000000
    7    7    7 00000111
   10    a   12 00001010
   64   40  100 01000000
  255   ff  377 11111111

Fixed-point numbers

~f formats a number with a decimal point. Its first parameter is the width of the whole field and the second the number of digits after the point. Without parameters, it prints all the digits.

fixed.scm
(use-modules (ice-9 format))

(define pi 3.14159265)

(format #t "[~f]~%" pi)
(format #t "[~,2f]~%" pi)
(format #t "[~10,2f]~%" pi)
(format #t "[~10,4f]~%" (- pi))
(format #t "[~,2f] [~,2f]~%" 2 1/3)
(format #t "[~,0f]~%" 2.5)
(format #t "[~,2f]~%" 1234567.891)
(format #t "[~8,2f]~%" 1234567.891)
(format #t "[~8,2,,'*f]~%" 1234567.891)

~,2f gives two decimal places, and ~10,2f puts them in a field of ten characters. ~f also accepts integers and exact rationals: 2 becomes 2.00 and 1/3 0.33. With zero decimal places, the result keeps the decimal point, as in 3.. A number wider than the field is printed in full, unless the fourth parameter gives an overflow character; then the whole field is filled with it, which shows clearly that the value did not fit.

$ guile fixed.scm
[3.14159265]
[3.14]
[      3.14]
[   -3.1416]
[2.00] [0.33]
[3.]
[1234567.89]
[1234567.89]
[********]

Rounding

Inexact numbers are stored in binary, and most decimal fractions have no exact binary form. This affects rounding, and format behaves differently from the round procedure.

rounding.scm
(use-modules (ice-9 format))

(format #t "~,2f ~,2f ~,2f~%" 2.675 1.005 0.125)
(display (inexact->exact 2.675))
(newline)
(display (< (inexact->exact 2.675) 2675/1000))
(newline)

(display (list (round 2.5) (round 3.5) (round -2.5)))
(newline)

(define (round-to x places)
  (let ((factor (expt 10 places)))
    (/ (round (* (inexact->exact x) factor)) factor)))

(display (round-to 2.675 2))
(display " ")
(display (exact->inexact (round-to 2.675 2)))
(newline)
(display (round-to 0.125 2))
(display " ")
(display (exact->inexact (round-to 0.125 2)))
(newline)
(display (exact->inexact (round-to 3.14159 3)))
(newline)

(define sum (+ 0.1 0.2))
(display sum)
(newline)
(format #t "~,2f~%" sum)

format rounds the printed decimal digits, and a 5 in the first dropped place rounds up: 2.675 becomes 2.68. The number actually stored for 2.675 is slightly less than 2.675, as its exact value shows. round rounds halves to the even neighbour, so 2.5 becomes 2.0. round-to works with the exact value of its argument. It rounds 2.675 down to 2.67, because the stored value is below the half, and 0.125, which is stored exactly, to the even 0.12. The result is an exact fraction, which exact->inexact turns into a decimal. The sum of 0.1 and 0.2 shows the binary error that display reveals and ~,2f hides. For amounts of money, calculate with exact numbers or integer cents and format only the final result.

$ guile rounding.scm
2.68 1.01 0.13
3011782250804019/1125899906842624
#t
(2.0 4.0 -2.0)
267/100 2.67
3/25 0.12
3.142
0.30000000000000004
0.30

Scientific notation and money

~e writes a number with an exponent, which suits very large and very small values. ~$ is the monetary directive: it prints two decimal places by default.

scientific.scm
(use-modules (ice-9 format))

(format #t "~e~%" 12345.678)
(format #t "~,3e~%" 12345.678)
(format #t "~,2e~%" 6.02214076e23)
(format #t "~,2e~%" 0.000123)
(format #t "~e~%" 100)

(format #t "~$~%" 3.5)
(format #t "~@$~%" 3.5)
(format #t "~,,10$~%" 1234.5)

(define prices '(("coffee" . 2.8) ("cake" . 4.25) ("tea" . 1.9)))

(for-each (lambda (item)
            (format #t "~a: ~$ EUR~%" (car item) (cdr item)))
          prices)
(format #t "total: ~$ EUR~%" (apply + (map cdr prices)))

The second parameter of ~e is the number of digits after the point of the mantissa. The exponent is written with an uppercase E and a sign. For ~$, the first parameter is the number of decimal places, the second the minimum number of digits before the point, and the third the width, so ~,,10$ right-aligns the amount in ten characters. @ adds the sign. The price list prints every amount with two decimal places, also 2.8 and 1.9.

$ guile scientific.scm
1.2345678E+4
1.235E+4
6.02E+23
1.23E-4
1.0E+2
3.50
+3.50
   1234.50
coffee: 2.80 EUR
cake: 4.25 EUR
tea: 1.90 EUR
total: 8.95 EUR

Aligned columns

A table lines up when every column has a fixed width. ~10a pads text on the right, so it is aligned to the left, and ~10@a pads on the left. Numbers use ~d and ~f with a width.

columns.scm
(use-modules (ice-9 format))

(format #t "[~10a]~%" "left")
(format #t "[~10@a]~%" "right")

(define items
  '(("Notebook" 3 2.5)
    ("Fountain pen" 1 24.9)
    ("Ink" 2 6.75)
    ("Pencil" 12 0.6)))

(define (line-total item)
  (* (cadr item) (caddr item)))

(format #t "~15a ~5@a ~8@a ~9@a~%" "Item" "Qty" "Price" "Total")
(format #t "~a~%" (make-string 40 #\-))
(for-each (lambda (item)
            (format #t "~15a ~5d ~8,2f ~9,2f~%"
                    (car item) (cadr item) (caddr item) (line-total item)))
          items)
(format #t "~a~%" (make-string 40 #\-))
(format #t "~15a ~24,2f~%" "Sum" (apply + (map line-total items)))

The header uses the same widths as the rows: fifteen characters for the name and five, eight, and nine for the numbers, with one space between the columns. The header texts are right-aligned with ~@a to match the numbers below them. make-string draws the lines. The sum is printed in a field of 24 characters, which spans the last three columns together with their separating spaces, so it ends under the totals.

$ guile columns.scm
[left      ]
[     right]
Item              Qty    Price     Total
----------------------------------------
Notebook            3     2.50      7.50
Fountain pen        1    24.90     24.90
Ink                 2     6.75     13.50
Pencil             12     0.60      7.20
----------------------------------------
Sum                                53.10

Numbers in words and Roman numerals

~r without a base writes a number in English words. The : modifier gives an ordinal, @ a Roman numeral, and :@ an old-style Roman numeral. A Roman numeral converter is also a short exercise in Scheme.

words.scm
(use-modules (ice-9 format))

(format #t "~r~%" 1234)
(format #t "~r~%" -15)
(format #t "~:r~%" 21)
(format #t "~@r~%" 1994)
(format #t "~:@r~%" 1994)

(define roman-digits
  '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
    (100 . "C") (90 . "XC") (50 . "L") (40 . "XL")
    (10 . "X") (9 . "IX") (5 . "V") (4 . "IV") (1 . "I")))

(define (roman n)
  (let loop ((n n) (digits roman-digits) (acc ""))
    (cond ((= n 0) acc)
          ((>= n (caar digits))
           (loop (- n (caar digits)) digits (string-append acc (cdar digits))))
          (else (loop n (cdr digits) acc)))))

(for-each (lambda (n)
            (format #t "~4d ~10a ~a~%" n (roman n) (format #f "~@r" n)))
          '(4 9 14 1994 2026 3999))

Old-style numerals have no subtraction, so 1994 is written with DCCCC and IIII instead of CM and IV. roman uses an association list of values and symbols ordered from the largest; the pairs such as (900 . "CM") handle the subtraction rule. The loop takes the largest value that fits, appends its symbol, and moves to the next value when it no longer fits. The table compares the result with ~@r, which format returns as a string when its destination is #f.

$ guile words.scm
one thousand, two hundred thirty-four
minus fifteen
twenty-first
MCMXCIV
MDCCCCLXXXXIIII
   4 IV         IV
   9 IX         IX
  14 XIV        XIV
1994 MCMXCIV    MCMXCIV
2026 MMXXVI     MMXXVI
3999 MMMCMXCIX  MMMCMXCIX

Human-readable sizes

The final example lists files with their sizes in bytes, in binary units, and as a percentage of the total, as a disk usage tool does.

sizes.scm
(use-modules (ice-9 format))

(define units '("B" "KiB" "MiB" "GiB" "TiB"))

(define (human-size bytes)
  (let loop ((size bytes) (units units))
    (if (or (< size 1024) (null? (cdr units)))
        (if (string=? (car units) "B")
            (format #f "~d ~a" size (car units))
            (format #f "~,1f ~a" size (car units)))
        (loop (/ size 1024) (cdr units)))))

(define files
  '(("notes.txt" . 812)
    ("photo.jpg" . 2457600)
    ("backup.tar" . 75497472)
    ("report.pdf" . 1536)))

(define total (apply + (map cdr files)))

(for-each (lambda (file)
            (format #t "~12a ~16:d ~10@a ~6,1f%~%"
                    (car file) (cdr file) (human-size (cdr file))
                    (* 100.0 (/ (cdr file) total))))
          files)
(format #t "~12a ~16:d ~10@a~%" "total" total (human-size total))

human-size divides the size by 1024 until it is below 1024 or the units run out. Exact division keeps the value as a fraction, which ~,1f prints with one decimal place; plain bytes are printed as an integer with ~d. The table shows the bytes with ~16:d, the readable size right-aligned with ~10@a, and the share with ~6,1f followed by a percent sign, which is an ordinary character in the template.

$ guile sizes.scm
notes.txt                 812      812 B    0.0%
photo.jpg           2,457,600    2.3 MiB    3.2%
backup.tar         75,497,472   72.0 MiB   96.8%
report.pdf              1,536    1.5 KiB    0.0%
total              77,957,420   74.3 MiB

Source

Formatted Output — GNU Guile Reference Manual

Converting Numbers To and From Strings — GNU Guile Reference Manual

In this article we have printed integers in fields with padding and signs, grouped digits, written numbers in other bases, formatted fixed-point numbers, examined rounding, used scientific notation and the monetary directive, aligned columns in a table, written numbers in words and Roman numerals, and printed human-readable file sizes. The ports and output article covers the other format directives, and the string processing article pads and aligns text.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Scheme tutorials.