Rounding a floating point number
- From: jacob navia <jacob@xxxxxxxxxx>
- Date: Mon, 25 Feb 2008 11:18:24 +0100
Hi
"How can I round a number to x decimal places" ?
This question keeps appearing. I would propose the following
solution
#include <float.h>
#include <math.h>
double roundto(double x, int digits)
{
int sgn=1;
if (x == 0)
return 0;
if (digits > DBL_DIG)
digits = DBL_DIG;
else if (digits < 1)
digits = 1;
if(x < 0.0) {
sgn = -sgn;
x = -x;
}
double p = floorl(log10l(x));
p--;
p = digits-p;
double pow10 = pow(10.0, p);
return sgn*floor(x*pow10+0.5)/pow10;
}
long double roundtol(long double x, int digits)
{
int sgn=1;
if (x == 0)
return 0;
if (digits > LDBL_DIG)
digits = LDBL_DIG;
else if (digits < 1)
digits = 1;
if(x < 0.0) {
sgn = -sgn;
x = -x;
}
long double p = floorl(log10l(x));
p--;
p = digits-p;
long double pow10 = powl(10.0, p);
return sgn*floorl(x*pow10+0.5)/pow10;
}
#include <stdio.h>
int main(void)
{
double d = 1.7888889988996678;
long double ld = 1.7888889988996678998877L;
for (int i = 0; i<=DBL_DIG;i++) {
printf("i=%d: %.15g\n",i,roundto(d,i));
}
printf("\n 1.7888889988996678\n");
for (int i = 0; i<=LDBL_DIG;i++) {
printf("i=%d: %.18Lg\n",i,roundtol(ld,i));
}
printf("\n 1.7888889988996678998877L\n");
return 0;
}
--------------------------------------------------------------------
I would propose it to add it to the FAQ.
--
jacob navia
jacob at jacob point remcomp point fr
logiciels/informatique
http://www.cs.virginia.edu/~lcc-win32
.
- Follow-Ups:
- Re: Rounding a floating point number
- From: CBFalconer
- Re: Rounding a floating point number
- From: user923005
- Re: Rounding a floating point number
- From: user923005
- Re: Rounding a floating point number
- From: Keith Thompson
- Re: Rounding a floating point number
- From: Richard Heathfield
- Re: Rounding a floating point number
- Prev by Date: Re: Sorting
- Next by Date: Re: Freeing memory - will it be available immediately
- Previous by thread: Freeing memory - will it be available immediately
- Next by thread: Re: Rounding a floating point number
- Index(es):
Relevant Pages
|