I have an integral value:

cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq

I assign it to a shell variable:

CPU_FREQ=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq)

I want to display it in scientific format from within a shell script using bash. In addition, I need to use it as an argument to a program. Here's what I want:

echo $CPU_FREQ

There are some hits on the web, but its not obvious to me how to modify them because I usually work with C/C++/Objective C. See, for example, bash display integral in scientific notation and Remove scientific notation bash script.

Is there a way to convert an integral into scientific notation?

Or how do I display the value scientific notation?

  • 2
    printf "%e\n" "$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq)" – cuonglm Jan 28 '16 at 6:52
  • @jww 2.4+1e9 does not make sense here (it would be equal to 1000000002.4). Do you mean 2.4e+6? – Dubu Jan 28 '16 at 8:17

This should be as simple as:

printf "%g" $(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq)

Or, using perl:

cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq | perl -e 'printf("%g\n", <>)'

The format you're requesting seems a bit strange, but these two examples will print a number using scientific notation.

  • "The format you're requesting seems a bit strange" - Why? The benchmark program requires scientific notation. If I use an integral, then it makes the benchmark program think the CPU speed is 10^18 rather than 10^9. – user56041 Jun 29 '16 at 1:11

Indeed as @Jan mentioned, you can use printf with %e. @Will mentioned the option %g, but that's not necessarily scientific notation (see below).

It's based on C's printf that you already know.

CPU_FREQ=$(printf "%e" $(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq))

printf command works like this:

printf "print a float variable %f, or an integer literal. %d" $var 2

You can use either %g, %e, %G or %E. also, with optional extra literal integer parameters a,b, e.g.: %a.bf

Briefly, the optional paramater a is the minimum width size (which are ignored if forwarding the output in a variable).

%.be prints it with exactly b decimals, rounding of padding with zeros if necessary. %.bg prints the result with b significant figures, ignoring all trailing zeros. (It can also be thought as the shorter between %f and %e two, but is it worth noticing again, it is without trailing zeros.)


printf "%e\n"  $R
printf "%g\n" $R

printf "%e\n"  $R
printf "%g\n" $R

printf "%e\n"  $R
printf "%g\n" $R

printf "%e\n"  $R
printf "%g\n" $R 

(%G and %E are just like %g and %e, but they print the output in upper case instead, which only applies to the e that turns into an E.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy