Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A C routine to round a float to n significant digits?

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

like image 644
steviekm3 Avatar asked Oct 26 '12 20:10

steviekm3


People also ask

How do you round to significant digits?

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.

What are the rules to round off a number to n 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.

How do you round off a float value in C#?

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);

How many significant digits does a float have?

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.


2 Answers

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.

like image 199
Daniel Gehriger Avatar answered Oct 18 '22 07:10

Daniel Gehriger


#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

like image 20
David Schwartz Avatar answered Oct 18 '22 07:10

David Schwartz