Channels ▼
RSS

Open Source

C Snippet #2


Q: HOW DO I... round floating-point values in C?

A: This header file Snippet contains macros to round floating-point values in two different manners. The iround() macro rounds the value to the nearest integer. The fround() macro rounds the value to a specified number of decimal points.



/*
** rounding macros by Dave Knapp
*/

/* round to integer */

#define iround(x) floor((x)+0.5)

/* round number n to d decimal points */

#define fround(n,d)  (floor((n)/pow(.1,(d))+.5)*pow(.1,(d)))

Update to C Snippet #2


/**************************************************/
/**** round.h ****/

/*
** rounding macros by Dave Knapp, Thad Smith, Jon Strayer, & Bob Stout
*/

#ifndef ROUND__H
#define ROUND__H

#include <math.h>

#if defined(__cplusplus) && __cplusplus

/*
** Safe C++ inline versions
*/

/* round to integer */

template<class T> inline int iround(T x)
{
      // This needs to be modified if passing long doubles
      return (int)floor(double(x) + 0.5);
}

/* round number n to d decimal points */

inline double fround(double n, unsigned d)
{
      return floor(n * pow(10., d) + .5) / pow(10., d);
}

#else // C

/*
** NOTE: These C macro versions are unsafe since arguments are referenced
**       more than once.
**
**       Avoid using these with expression arguments to be safe.
*/

/*
** round to integer
*/

#define iround(x) ((int)floor((double)(x) + 0.5))

/*
** round number n to d decimal points
*/

#define fround(n,d) (floor((n)*pow(10.,(d))+.5)/pow(10.,(d)))

#endif // C/C++

#endif /* ROUND__H */


/**********************************************/
/**** rndtst.c ****/

/*
**  Demo/test main() function for ROUND.H
*/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "round.h"

int main(void)
{
      float fx[] = {-5/3.0, -4/3.0, -2/3.0, -1/3.0, 1/3.0, 2/3.0, 4/3.0, 5/3.0};
      double dx[] = {-5/3.0, -4/3.0, -2/3.0, -1/3.0, 1/3.0, 2/3.0, 4/3.0, 5/3.0};
      double phi = (1 + sqrt(5.0)) / 2;
      int i;

      for (i = 0; i < 8; ++i)
            printf("%d: float: iround(%.6g) = %d\n", i+1, fx[i], iround(fx[i]));
      for (i = 0; i < 8; ++i)
            printf("%d: double: iround(%.12g) = %d\n", i+1, dx[i], iround(dx[i]));

      for (i = 1; i < 5; i++)
      {
            int x = i * 2;

            printf("fround(phi, %d) = %.9g\n", x, fround(phi, x));
      }
      return EXIT_SUCCESS;
}


/************************************************/
/**** rndtst.out ****/

1: float: iround(-1.66667) = -2
2: float: iround(-1.33333) = -1
3: float: iround(-0.666667) = -1
4: float: iround(-0.333333) = 0
5: float: iround(0.333333) = 0
6: float: iround(0.666667) = 1
7: float: iround(1.33333) = 1
8: float: iround(1.66667) = 2
1: double: iround(-1.66666666667) = -2
2: double: iround(-1.33333333333) = -1
3: double: iround(-0.666666666667) = -1
4: double: iround(-0.333333333333) = 0
5: double: iround(0.333333333333) = 0
6: double: iround(0.666666666667) = 1
7: double: iround(1.33333333333) = 1
8: double: iround(1.66666666667) = 2
fround(phi, 2) = 1.62
fround(phi, 4) = 1.618
fround(phi, 6) = 1.618034

More C Snippets

All the code in C Snippets is either public domain or freeware and may therefore freely be used by the C programming community without restrictions. In most cases, if the original author is someone other than myself he or she will be identified. Thanks to all who have contributed to this collection over the years. I hope Dr. Dobb's readers will find these useful.

— Bob Stout
rbs@snippets.org


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video