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.
Asked
Active
Viewed 2,467 times
1 Answers
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
- 17,283
/usr/bin/printf
, because that is exceptionally well defined - does that make sense? – Volker Siegel Oct 14 '14 at 12:29printf
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/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 outcsh
does not have the builtin: ($ csh -c builtins | grep -Fx printf
). – Volker Siegel Oct 14 '14 at 12:50