Rounding a floating point number



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
.



Relevant Pages

  • Re: Preprocessor limitation workarounds
    ... #ifndef RADIX ... typedef unsigned short int digit_t; ... # error "Unable to represent the product of two digits" ...
    (comp.lang.c)
  • Re: binary number
    ... Integer literals ... An integer literal is a sequence of digits that has no period ... specifies its base and a suffix that specifies its type. ... these types in which its value can be represented: int, ...
    (comp.lang.cpp)
  • Re: System.Math.Round bug (repost)
    ... Round(double value, int digits) ... It always seems to use the Round(decimal value, int decimals) version, no ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: help me
    ... to exponential...if i use int then its not accepting more than 4 ... I think you've misunderstood your assignment. ... If you want the whole entry (17 digits) into *one* variable, ... This means that it's sufficient with an array of int's (even with bytes, ...
    (comp.lang.java.help)
  • Re: algorithm for brute force an variable lenght array
    ... (chromossomeint will range from 0 to 4) ... In an odometer, there are a series of wheels that count up from 0 ... digits ... OVERFLOW if the odometer overflows, ...
    (comp.lang.c)