Skip to content

Number formatting

The --ofmt flag

The command-line option --ofmt {format string} is the global number format for all numeric fields. Examples:

--ofmt %.9e --ofmt %.6f --ofmt %.0f

These are just familiar printf formats. (TODO: write about type-checking once that's implemented.) Additionally, if you use leading width (e.g. %18.12f) then the output will contain embedded whitespace, which may not be what you want if you pipe the output to something else, particularly CSV. I use Miller's pretty-print format (mlr --opprint) to column-align numerical data.

echo 'x=3.1,y=4.3' | mlr --ofmt '%8.3f' cat
x=   3.100,y=   4.300
echo 'x=3.1,y=4.3' | mlr --ofmt '%11.8e' cat

The format-values verb

To separately specify formatting for string, int, and float fields, you can use the format-values verb -- see that section for examples.

The fmtnum and hexfmt functions

To apply formatting to a single field, you can also use fmtnum function within mlr put. For example:

echo 'x=3.1,y=4.3' | mlr put '$z=fmtnum($x*$y,"%08f")'
echo 'x=0xffff,y=0xff' | mlr put '$z=fmtnum(int($x*$y),"%08x")'

Input conversion from hexadecimal is done automatically on fields handled by mlr put and mlr filter as long as the field value begins with 0x. To apply output conversion to hexadecimal on a single column, you may use fmtnum, or the keystroke-saving hexfmt function. Example:

echo 'x=0xffff,y=0xff' | mlr put '$z=$x*$y'
echo 'x=0xffff,y=0xff' | mlr put '$z=hexfmt($x*$y)'