Hi
Does any body know, how to round a double value with a specific number
of digits after the decimal points?
A function like this:
RoundMyDouble (double &value, short numberOfPrecisions)
It then updates the value with numberOfPrecisions after the decimal
point.
This sort of works most of the time:
#include <math.h>
double fround(const double nn, const unsigned d)
{
const long double n = nn;
const long double ld = (long double) d;
return (double) (floorl(n * powl(10.0L, ld) + 0.5L) / powl(10.0L,
ld));
}
#ifdef UNIT_TEST
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
int main(void)
{
double pi = 3.1415926535897932384626433832795;
unsigned digits;
for (digits = 0; digits <= DBL_DIG; digits++) {
printf("Rounding by printf gives: %20.*f\n",
digits, pi);
printf("Rounding approximation by function gives: %20.*f\n",
DBL_DIG, fround(pi, digits));
}
return 0;
}
#endif
/*
C:\tmp>cl /W4 /Ox /DUNIT_TEST round.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762
for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.
round.c
Microsoft (R) Incremental Linker Version 8.00.50727.762
Copyright (C) Microsoft Corporation. All rights reserved.
/out:round.exe
round.obj
C:\tmp>round
Rounding by printf gives: 3
Rounding approximation by function gives: 3.000000000000000
Rounding by printf gives: 3.1
Rounding approximation by function gives: 3.100000000000000
Rounding by printf gives: 3.14
Rounding approximation by function gives: 3.140000000000000
Rounding by printf gives: 3.142
Rounding approximation by function gives: 3.142000000000000
Rounding by printf gives: 3.1416
Rounding approximation by function gives: 3.141600000000000
Rounding by printf gives: 3.14159
Rounding approximation by function gives: 3.141590000000000
Rounding by printf gives: 3.141593
Rounding approximation by function gives: 3.141593000000000
Rounding by printf gives: 3.1415927
Rounding approximation by function gives: 3.141592700000000
Rounding by printf gives: 3.14159265
Rounding approximation by function gives: 3.141592650000000
Rounding by printf gives: 3.141592654
Rounding approximation by function gives: 3.141592654000000
Rounding by printf gives: 3.1415926536
Rounding approximation by function gives: 3.141592653600000
Rounding by printf gives: 3.14159265359
Rounding approximation by function gives: 3.141592653590000
Rounding by printf gives: 3.141592653590
Rounding approximation by function gives: 3.141592653590000
Rounding by printf gives: 3.1415926535898
Rounding approximation by function gives: 3.141592653589800
Rounding by printf gives: 3.14159265358979
Rounding approximation by function gives: 3.141592653589790
Rounding by printf gives: 3.141592653589793
Rounding approximation by function gives: 3.141592653589793
*/