Suppose I have a float
. I would like to round it to a certain number of significant digits.
In my case n=6
.
So say float was f=1.23456999;
round(f,6)
would give 1.23457
f=123456.0001
would give 123456
Anybody know such a routine ?
Here it works on website: http://ostermiller.org/calc/significant_figures.html
It rounds to the most important figure in the number. To round to a significant figure: look at the first non-zero digit if rounding to one significant figure. look at the digit after the first non-zero digit if rounding to two significant figures.
Rules for Rounding-off a NumberDiscard all digits to the right of nth significant digit. less than half a unit in nthplace, leave the nth digit unchanged. greater than half a unit in the nth place, increase the nth digit by unity.
This method is used to rounds a double precision floating-point value to the nearest integer. A parameter specifies how to round the value if it is midway between two numbers. Syntax: public static double Round (double val, MidpointRounding mode);
Float values have between 6 and 9 digits of precision, with most float values having at least 7 significant digits. Double values have between 15 and 18 digits of precision, with most double values having at least 16 significant digits.
Multiply the number by a suitable scaling factor to move all significant digits to the left of the decimal point. Then round and finally reverse the operation:
#include <math.h>
double round_to_digits(double value, int digits)
{
if (value == 0.0) // otherwise it will return 'nan' due to the log10() of zero
return 0.0;
double factor = pow(10.0, digits - ceil(log10(fabs(value))));
return round(value * factor) / factor;
}
Tested: http://ideone.com/fH5ebt
Buts as @PascalCuoq pointed out: the rounded value may not exactly representable as a floating point value.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *Round(float f, int d)
{
char buf[16];
sprintf(buf, "%.*g", d, f);
return strdup(buf);
}
int main(void)
{
char *r = Round(1.23456999, 6);
printf("%s\n", r);
free(r);
}
Output is:
1.23457
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With