# Using printf to round 49.765 to 49.77?

49.765 is my output from a ring of commands. I want to use print f to round it by two decimal figures to 49.77.

What is the code for it?

• Please clarify your question: do you mean `printf(1)` here (the shell command) or `printf(3)` (the C library function)? My answer below gives the answer for `printf(1)`, which would be on-topic here on Unix.SE. Harshit's answer gives the answer for `printf(3)`, which is really more of a Stack Overflow type of question. – Warren Young Oct 1 '16 at 4:47

## 2 Answers

``````\$ x=49.765
\$ printf "%.2f" \$(echo "\$x + 0.005" | bc)
``````

You have to use external commands because there is no built-in rounding feature in `printf(1)`, and the POSIX shell doesn't have built-in floating-point arithmetic.

To round to the nearest decimal digit, you add 0.5 and truncate. To round to the nearest tenth, you divide the "nudge factor" by 10, and so forth.

This lack of built-in facilities is what often pushes people to use something like Perl rather than shell:

``````\$ perl -e 'printf "%.2f", 49.765 + 0.005'
``````

Same thing, but all handled by a single process.

You can use following command for rounding off.

float number = 49.765; printf("%0.2f", number);

You should be able to get the 2 figures after decimal point.

But this will just print, it will not update the value. If you would like to change the value of the variable then you should use below.

``````#include <math.h>

float val = 49.765;

float rounded_down = floorf(val * 100) / 100;   /* Result: 49.76 */
float nearest = roundf(val * 100) / 100;  /* Result: 49.77 */
float rounded_up = ceilf(val * 100) / 100;      /* Result: 49.77 */
``````

Notice that there are three different rounding rules you might want to choose: round down (ie, truncate after two decimal places), rounded to nearest, and round up. Usually, you want round to nearest.

As several others have pointed out, due to the quirks of floating point representation, these rounded values may not be exactly the "obvious" decimal values, but they will be very very close.