String formatting with printf:
Jump to navigation
Jump to search
Problems.
- How can I print out a text table?
- How can I format numbers with only 2 decimals?
- How can I pad a number to fixed with putting zeros in front of it?
- ...
Solution. These and more little everyday problems can be solved with String>>printf:
. See the examples below.
"to use :printf you must load this package"
Feature require:'Printf'
". print an integer"
'a number : %d' printf: 123. " 'a number : 123' "
". pad an integer with starting zeros to make it a deault lenght"
'padding a number: %05d' printf: 123. "=> 'padding a number: 00123' "
". print a floating point with as many decimals you wish"
'3 decimals: %.3f' printf: 123.456789. "=> '3 decimals: 123.456' "
". fixed length strings, good for tables "
'%15s %15s %10s' printf: {'Name'. 'Last name'. 'mail'}.
"=> ' Name Last name mail' "
". fixed length strings, align left, good for tables "
'%-15s %-15s %-10s' printf: {'Name'. 'Last name'. 'mail'}.
"=> 'Name Last name mail ' "
". BROKEN-at-2025-05-05 --- classic newline "
'line1\nline2' printf: nil. "=> 'line1
line2' "
- Thousand separators and locales
". print an integer with thousand separators "
'%_d' printf: {1234}. "=> '1_234' "
". print a float number with default thousand separator, tested for %f and %d. "
'%_0.2f' printf: {1234.567}. "=> '1_234.56' "
". Change format for thousand separator and decimal separator "
PrintfNumberFormatDescriptor setUserThousandSeparatorTo: $, .
'%_0.2f' printf: {1234.567}. "=> '1,234.56' "
". now let's print the number in the way it is considered 'normal' in Italy, for example "
PrintfNumberFormatDescriptor setUserThousandSeparatorTo: $. .
PrintfNumberFormatDescriptor setUserDecimalSeparatorTo: $, .
'%_0.2f' printf: {1234.567}. "=> '1.234,56' "
". and let's put back the default configuaration "
PrintfNumberFormatDescriptor setUserThousandSeparatorTo: nil .
PrintfNumberFormatDescriptor setUserDecimalSeparatorTo: nil .
'_0.2f' printf: {1234.567}. "=> '1_234.56' "
Things that still do not work or are not implemented
- Formatting a number in scientific notation: `%e`, `%E`, `%g`.
"?scientifig notation -- broken ?"
'scientific: %e' printf: 123345.1234. "=> 'scientific: 123345.1' "
- Formatting a number in scientific notation: `%e`, `%E`, `%g`.
"?scientifig notation -- broken ?"
'scientific: %e' printf: 123345.1234. "=> 'scientific: 123345.1' "
- Formatting a long number splitting it on thousands
%'
. - Align a string the center of a fixed space. (this is not available in C but it would be nice to have)
Dr. Nicola Mingotti last checked on 05-May-2025. Tested in Cuis rolling release.