William Breathitt Gray
William Breathitt Gray

Reputation: 11986

Round to nearest ten using printf

The precision specifier for floating point values given to printf allows a programmer to specify the number of digits to be printed after the decimal place. Does printf have a similar precision specifier which allows the programmer to specify how many digits before the decimal point to round the value?

For example, if I pass 157 to printf, I want the value 160 to be printed to the screen if I tell it to round to the nearest ten.

Upvotes: 0

Views: 1564

Answers (4)

chux
chux

Reputation: 153650

I like the myRound(157, 10) solution, but thought I would add:

printf("%d0\n", (n+5)/10);   // int n;
printf("%.0f0\n", x/10);     // double x; (fails for INF, NAN)

Upvotes: 0

Alexandros
Alexandros

Reputation: 3064

No. The closest you can probably get with printf is by using scientific notation:

printf("%.1e\n", 157.0);

This will print 1.6e+02, which is definitely not what you want.

Upvotes: 1

Kninnug
Kninnug

Reputation: 8053

printf doesn't alter the data, the format specifiers only specify how it's displayed. If you give printf 157 it will print 157 in some form or another.

Check out the rounding functions in the C math library for rounding functions.

Upvotes: 3

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272567

So far as I know, there's no way to get printf to do that. You'd have to round the value manually before passing it to printf. For example:

printf("%d\n", myRound(157, 10));

int myRound(int x, int b) {
    return ((x + b/2) / b) * b;  // TODO: handling for overflow, etc.
}

Upvotes: 4

Related Questions