一个C例程将浮点数舍入到n位有效数字?

时间:2012-10-26 20:48:48

标签: c++ c floating-point

假设我有float。我想将它四舍五入到一定数量的有效数字。

就我而言n=6

所以说浮动是f=1.23456999;

round(f,6)会给1.23457

f=123456.0001会给123456

有人知道这样的例行公事吗?

此处适用于网站:http://ostermiller.org/calc/significant_figures.html

6 个答案:

答案 0 :(得分:7)

将数字乘以合适的比例因子,将所有有效数字移动到小数点的左侧。然后回合并最终反转操作:

#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;   
}

经过测试:http://ideone.com/fH5ebt

但是@PascalCuoq指出:舍入值可能无法完全表示为浮点值。

答案 1 :(得分:4)

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

输出是:

  

1.23457

答案 2 :(得分:3)

这样的事情应该有效:

double round_to_n_digits(double x, int n)
{ 
    double scale = pow(10.0, ceil(log10(fabs(x))) + n);

    return round(x * scale) / scale;
}

或者您可以使用sprintf / atof转换为字符串然后再返回:

double round_to_n_digits(double x, int n)
{ 
    char buff[32];

    sprintf(buff, "%.*g", n, x);

    return atof(buff);
}

上述两项功能的测试代码:http://ideone.com/oMzQZZ

<小时/> 注意,在某些情况下,可能会观察到不正确的舍入,例如,正如@clearScreen在下面的评论中指出的那样,13127.15被舍入为13127.1而不是 13127.2。

答案 3 :(得分:2)

如果要将float打印到字符串,请使用简单sprintf()。要将其输出到控制台,您可以使用printf()

printf("My float is %.6f", myfloat);

这将输出带有6位小数的浮点数。

答案 4 :(得分:2)

这应该有效(浮点精度给出的噪声除外):

#include <stdio.h>
#include <math.h>

double dround(double a, int ndigits);

double dround(double a, int ndigits) {

  int    exp_base10 = round(log10(a));
  double man_base10 = a*pow(10.0,-exp_base10);
  double factor     = pow(10.0,-ndigits+1);  
  double truncated_man_base10 = man_base10 - fmod(man_base10,factor);
  double rounded_remainder    = fmod(man_base10,factor)/factor;

  rounded_remainder = rounded_remainder > 0.5 ? 1.0*factor : 0.0;

  return (truncated_man_base10 + rounded_remainder)*pow(10.0,exp_base10) ;
}

int main() {

  double a = 1.23456999;
  double b = 123456.0001;

  printf("%12.12f\n",dround(a,6));
  printf("%12.12f\n",dround(b,6));

  return 0;
}

答案 5 :(得分:-2)

  

打印到16位有效数字。

double x = -1932970.8299999994;
char buff[100];
snprintf(buff, sizeof(buff), "%.16g", x);
std::string buffAsStdStr = buff;

std::cout << std::endl << buffAsStdStr ;
相关问题