Say I have this number: 105000000, in this form I can't easily see how big it is, so using printf
at a prompt I try using the "scientific" notation:
% printf "%.3E" 105000000
1.050E+08
This is better but I would like to use an "engineering" notation where the output is formatted in powers of 103 millions, billions, trillions etc.
e.g. I want to format it to look like this:
105000 => 105.0E+03 (105 thousand)
105000000 => 105.0E+06 (105 million)
105000000000 => 105.0E+09 (105 billion)
...
can printf
do this?
Best Answer
I don't know of any
printf
implementation that does. Note that POSIX doesn't even guaranteeprintf '%E\n' 123
to work at all as support for floating point formats is optional.With several
printf
implementations, you can use%'f
to output thousand separators in locales that have one:With the
printf
builtin ofksh93
, you can also use%#d
for K/M/G... suffixes and%#i
for Ki/Mi/Gi ones:(note however that you can't change the precision and the transition from
Ki
toMi
for instance is at 1000 Ki, not 1024 Ki which can be surprising if you're used to the GNU format (like in GNUls -lh
). It's also limited to integer numbers up to 263-1 (8Ei - 1)).As to how to implement it by hand, with
zsh
:And then:
Note that in
zsh
like in many other languages, operations involving floats are done in floating point arithmetics (with your processor'sdouble
type) while those involving integers only are done in integer arithmetics (with your processor'slong
type). That has some implications like:but also:
(though that's not specific to that
eng
function)Or as a POSIX shell function using POSIX
bc
, so allowing arbitrary precision:(with a 1e-15 shift to offset rounding errors when calculating log10(n) for the exponent for values of n like 0.001)
Here with the first argument being taken as the scale:
Note that
bc
itself doesn't understand the engineering notation, you have to write: