2

I have a float number stored in a variable $temp, like 3.046789. How we can round this number with 2 digits precision and the result I need is 3.05. The script I have is a csh script.

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175

1 Answers1

3

You can use the command printf to format numbers in lots of ways, just like with the C function printf():

To make it independent of the shell used, run /usr/bin/printf

$ LC_ALL=C /usr/bin/printf '%.2f\n' 3.046789
3.05

The syntax of the format is described in the man page of the library function: man 3 printf.

Not sure about the variable handling in csh.

Additionally, printf can be available as a shell builtin command that does the same, like in bash.

Volker Siegel
  • 16,983
  • 5
  • 52
  • 79
  • @terdon It's more correct with the edit, but the idea for mentioning the builtins only at the end was that any builtin should do the same as `/usr/bin/printf`, because that is exceptionally well defined - does that make sense? – Volker Siegel Oct 14 '14 at 12:29
  • Absolutely, I just edited to clarify that `printf` is not always a builtin. I don't know if there is any flavor of printf that won't do what you describe in your answer, just that on systems running a sheel that has a builtin, that will be used before the separate binary. Admittedly, `csh`, does not seem to have the builtin so it makes no difference to the OP but other shells do. – terdon Oct 14 '14 at 12:37
  • @terdon Ah, now I see: I mentioned `/usr/bin/printf` directly before the command, explicitly implying that would use `/usr/bin/printf`, which is just wrong with a builtin - did not mean to have that implication. (btw, turns out `csh` does not have the builtin: (`$ csh -c builtins | grep -Fx printf`). – Volker Siegel Oct 14 '14 at 12:50
  • Now who wants to add this to the canonical question [How to do integer & float calculations, in bash or other languages/frameworks?](http://unix.stackexchange.com/q/40786/80216) (@terdon?) – G-Man Says 'Reinstate Monica' Oct 14 '14 at 18:53
  • @G-Man Good idea, I'll do! – Volker Siegel Oct 14 '14 at 18:55