# Number formatting

## The --ofmt flag

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

GENMD-CARDIFY
--ofmt %.9e --ofmt %.6f --ofmt %.0f
GENMD-EOF

These are just familiar `printf` formats -- as of Miller 6.0.0, supported options are those at
[https://pkg.go.dev/fmt](https://pkg.go.dev/fmt).  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.

GENMD-RUN-COMMAND
echo 'x=3.1,y=4.3' | mlr --ofmt '%8.3f' cat
GENMD-EOF

GENMD-RUN-COMMAND
echo 'x=3.1,y=4.3' | mlr --ofmt '%11.8e' cat
GENMD-EOF

## The format-values verb

To separately specify formatting for string, int, and float fields, you can use
the [`format-values`](reference-verbs.md#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`](reference-dsl-builtin-functions.md#fmtnum) function within `mlr
put`. For example:

GENMD-RUN-COMMAND
echo 'x=3.1,y=4.3' | mlr put '$z=fmtnum($x*$y,"%08f")'
GENMD-EOF

GENMD-RUN-COMMAND
echo 'x=0xffff,y=0xff' | mlr put '$z=fmtnum(int($x*$y),"%08x")'
GENMD-EOF

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`](reference-dsl-builtin-functions.md#hexfmt) function. Example:

GENMD-RUN-COMMAND
echo 'x=0xffff,y=0xff' | mlr put '$z=$x*$y'
GENMD-EOF

GENMD-RUN-COMMAND
echo 'x=0xffff,y=0xff' | mlr put '$z=hexfmt($x*$y)'
GENMD-EOF
