user2045143
user2045143

Reputation: 249

Rounding values less than 1 in C?

I am coding a graphical program in C and my cartesian values are in between [-1,1], I am having trouble rounding off values so that I can use them for plotting and further calculations. I know how to round values greater than 1 with decimals but this I haven't done before.

So how would I go about rounding values? For example,

.7213=.7

.7725= .8

.3666667=.4

.25=.2 or .3

.24=.2

Any suggestions would be gladly appreciated. :)

Upvotes: 2

Views: 526

Answers (2)

Thomas M. DuBuisson
Thomas M. DuBuisson

Reputation: 64740

In most languages, people often implement such rounding in an ad hoc way using *10, integral rounding, and /10. For example:

$ cat round.c
#include <stdio.h>
#include <stdint.h>

int main()
{
    fprintf(stderr, "%f\n",     ((double)  ((uint64_t) (10*0.7777))) / 10);
    return 0;
}

$ gcc round.c
[tommd@Vodka Test]$ ./a.out
0.700000

Upvotes: 1

Crowman
Crowman

Reputation: 25908

You don't (and can't, to any high degree of accuracy, due to how floating point values are stored) round floating point values, you can only output them to different degrees of precision. If you wanted all your float values rounded to 1 decimal place before using them in calculations, then do your calculations with integers, with everything multiplied by 10, then divide by 10 just before you display it.

Upvotes: 7

Related Questions