我一直绊脚石的格式符的printf()家庭的功能。我想要是可以打印一个双人(或浮动)与给予最大数量的数字后的小数点。如果我使用:

printf("%1.3f", 359.01335);
printf("%1.3f", 359.00999);

我得到

359.013
359.010

而不是所希望的

359.013
359.01

有人能帮帮我吗?

有帮助吗?

解决方案

使用普通的 printf 格式说明符无法做到这一点。你能得到的最接近的是:

printf("%.6g", 359.013); // 359.013
printf("%.6g", 359.01);  // 359.01

但是“.6”是数字宽度,所以

printf("%.6g", 3.01357); // 3.01357

打破它。

可以做的是 sprintf("%。20g")将数字转换为字符串缓冲区然后操纵字符串只有N个字符超过小数点。

假设您的数字在变量num中,以下函数将删除除第一个 N 小数之外的所有小数,然后去除尾随零(如果它们都是零,则删除小数点)。

char str[50];
sprintf (str,"%.20g",num);  // Make the number.
morphNumericString (str, 3);
:    :
void morphNumericString (char *s, int n) {
    char *p;
    int count;

    p = strchr (s,'.');         // Find decimal point, if any.
    if (p != NULL) {
        count = n;              // Adjust for more or less decimals.
        while (count >= 0) {    // Maximum decimals allowed.
             count--;
             if (*p == '\0')    // If there's less than desired.
                 break;
             p++;               // Next character.
        }

        *p-- = '\0';            // Truncate string.
        while (*p == '0')       // Remove trailing zeros.
            *p-- = '\0';

        if (*p == '.') {        // If all decimals were zeros, remove ".".
            *p = '\0';
        }
    }
}

如果您对截断方面不满意(将 0.12399 转换为 0.123 而不是将其舍入为 0.124 ),实际上可以使用 printf 已经提供的舍入功能。您只需要事先分析数字以动态创建宽度,然后使用它们将数字转换为字符串:

#include <stdio.h>

void nDecimals (char *s, double d, int n) {
    int sz; double d2;

    // Allow for negative.

    d2 = (d >= 0) ? d : -d;
    sz = (d >= 0) ? 0 : 1;

    // Add one for each whole digit (0.xx special case).

    if (d2 < 1) sz++;
    while (d2 >= 1) { d2 /= 10.0; sz++; }

    // Adjust for decimal point and fractionals.

    sz += 1 + n;

    // Create format string then use it.

    sprintf (s, "%*.*f", sz, n, d);
}

int main (void) {
    char str[50];
    double num[] = { 40, 359.01335, -359.00999,
        359.01, 3.01357, 0.111111111, 1.1223344 };
    for (int i = 0; i < sizeof(num)/sizeof(*num); i++) {
        nDecimals (str, num[i], 3);
        printf ("%30.20f -> %s\n", num[i], str);
    }
    return 0;
}

在这种情况下, nDecimals()的重点是正确计算字段宽度,然后使用基于该格式的格式字符串格式化数字。测试工具 main()显示了这一点:

  40.00000000000000000000 -> 40.000
 359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.010
 359.00999999999999090505 -> 359.010
   3.01357000000000008200 -> 3.014
   0.11111111099999999852 -> 0.111
   1.12233439999999995429 -> 1.122

一旦获得了正确的舍入值,您可以再次将其传递给 morphNumericString(),只需更改以下内容即可删除尾随零:

nDecimals (str, num[i], 3);

成:

nDecimals (str, num[i], 3);
morphNumericString (str, 3);

(或者在 nDecimals 的末尾调用 morphNumericString ,但是,在这种情况下,我可能只是将两者合并为一个函数),你最终得到了:

  40.00000000000000000000 -> 40
 359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.01
 359.00999999999999090505 -> 359.01
   3.01357000000000008200 -> 3.014
   0.11111111099999999852 -> 0.111
   1.12233439999999995429 -> 1.122

其他提示

要删除尾随零,您应该使用“%g”。格式:

float num = 1.33;
printf("%g", num); //output: 1.33

在问题澄清之后,抑制零并不是唯一被问到的东西,但是也需要将输出限制为三位小数。我认为单独使用sprintf格式字符串无法做到这一点。正如 Pax Diablo 指出的那样,需要进行字符串操作。

我喜欢的答案R.稍微调整了:

float f = 1234.56789;
printf("%d.%.0f", f, 1000*(f-(int)f));

'1000'确定的精度。

动力的0.5四舍五入。

编辑

好吧,这个答案是,编辑了几次,我失去了道我在想什么,几年前(和它最初并没有填补的所有标准)。因此,这里是一个新的版本(即填满所有的标准和可以处理负数字正确):

double f = 1234.05678900;
char s[100]; 
int decimals = 10;

sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
printf("10 decimals: %d%s\n", (int)f, s+1);

和试验的情况下:

#import <stdio.h>
#import <stdlib.h>
#import <math.h>

int main(void){

    double f = 1234.05678900;
    char s[100];
    int decimals;

    decimals = 10;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf("10 decimals: %d%s\n", (int)f, s+1);

    decimals = 3;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf(" 3 decimals: %d%s\n", (int)f, s+1);

    f = -f;
    decimals = 10;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf(" negative 10: %d%s\n", (int)f, s+1);

    decimals = 3;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf(" negative  3: %d%s\n", (int)f, s+1);

    decimals = 2;
    f = 1.012;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf(" additional : %d%s\n", (int)f, s+1);

    return 0;
}

的输出和试验:

 10 decimals: 1234.056789
  3 decimals: 1234.057
 negative 10: -1234.056789
 negative  3: -1234.057
 additional : 1.01

现在,所有标准得到满足:

  • 最大数量的小数点后的零是固定的
  • 尾随零被删除
  • 它的数学的权利(吗?)
  • 工作(现在)还在第一位小数是零

不幸的是这个答案是两衬 sprintf 不会返回。

我搜索字符串(从最右边开始)搜索 1 范围内的第一个字符到 9 (ASCII值 49 - 57 )然后 null (设置为 0 )每个char右边 - 见下文:

void stripTrailingZeros(void) { 
    //This finds the index of the rightmost ASCII char[1-9] in array
    //All elements to the left of this are nulled (=0)
    int i = 20;
    unsigned char char1 = 0; //initialised to ensure entry to condition below

    while ((char1 > 57) || (char1 < 49)) {
        i--;
        char1 = sprintfBuffer[i];
    }

    //null chars left of i
    for (int j = i; j < 20; j++) {
        sprintfBuffer[i] = 0;
    }
}

这样的事情怎么样(可能有需要调试的舍入错误和负值问题,留给读者练习):

printf("%.0d%.4g\n", (int)f/10, f-((int)f-(int)f%10));

它有点程序化,但至少它不会让你做任何字符串操作。

一个简单的解决方案,但它可以完成工作,分配已知的长度和精度,并避免使用指数格式(当使用%g时存在风险):

// Since we are only interested in 3 decimal places, this function
// can avoid any potential miniscule floating point differences
// which can return false when using "=="
int DoubleEquals(double i, double j)
{
    return (fabs(i - j) < 0.000001);
}

void PrintMaxThreeDecimal(double d)
{
    if (DoubleEquals(d, floor(d)))
        printf("%.0f", d);
    else if (DoubleEquals(d * 10, floor(d * 10)))
        printf("%.1f", d);
    else if (DoubleEquals(d * 100, floor(d* 100)))
        printf("%.2f", d);
    else
        printf("%.3f", d);
}

添加或删除“elses”如果你想要最多2位小数; 4位小数;等

例如,如果您想要2位小数:

void PrintMaxTwoDecimal(double d)
{
    if (DoubleEquals(d, floor(d)))
        printf("%.0f", d);
    else if (DoubleEquals(d * 10, floor(d * 10)))
        printf("%.1f", d);
    else
        printf("%.2f", d);
}

如果要指定保持字段对齐的最小宽度,请根据需要增加,例如:

void PrintAlignedMaxThreeDecimal(double d)
{
    if (DoubleEquals(d, floor(d)))
        printf("%7.0f", d);
    else if (DoubleEquals(d * 10, floor(d * 10)))
        printf("%9.1f", d);
    else if (DoubleEquals(d * 100, floor(d* 100)))
        printf("%10.2f", d);
    else
        printf("%11.3f", d);
}

您还可以将其转换为传递所需字段宽度的函数:

void PrintAlignedWidthMaxThreeDecimal(int w, double d)
{
    if (DoubleEquals(d, floor(d)))
        printf("%*.0f", w-4, d);
    else if (DoubleEquals(d * 10, floor(d * 10)))
        printf("%*.1f", w-2, d);
    else if (DoubleEquals(d * 100, floor(d* 100)))
        printf("%*.2f", w-1, d);
    else
        printf("%*.3f", w, d);
}

我在发布的一些解决方案中发现了问题。我根据上面的答案把它放在一起。它似乎对我有用。

int doubleEquals(double i, double j) {
    return (fabs(i - j) < 0.000001);
}

void printTruncatedDouble(double dd, int max_len) {
    char str[50];
    int match = 0;
    for ( int ii = 0; ii < max_len; ii++ ) {
        if (doubleEquals(dd * pow(10,ii), floor(dd * pow(10,ii)))) {
            sprintf (str,"%f", round(dd*pow(10,ii))/pow(10,ii));
            match = 1;
            break;
        }
    }
    if ( match != 1 ) {
        sprintf (str,"%f", round(dd*pow(10,max_len))/pow(10,max_len));
    }
    char *pp;
    int count;
    pp = strchr (str,'.');
    if (pp != NULL) {
        count = max_len;
        while (count >= 0) {
             count--;
             if (*pp == '\0')
                 break;
             pp++;
        }
        *pp-- = '\0';
        while (*pp == '0')
            *pp-- = '\0';
        if (*pp == '.') {
            *pp = '\0';
        }
    }
    printf ("%s\n", str);
}

int main(int argc, char **argv)
{
    printTruncatedDouble( -1.999, 2 ); // prints -2
    printTruncatedDouble( -1.006, 2 ); // prints -1.01
    printTruncatedDouble( -1.005, 2 ); // prints -1
    printf("\n");
    printTruncatedDouble( 1.005, 2 ); // prints 1 (should be 1.01?)
    printTruncatedDouble( 1.006, 2 ); // prints 1.01
    printTruncatedDouble( 1.999, 2 ); // prints 2
    printf("\n");
    printTruncatedDouble( -1.999, 3 ); // prints -1.999
    printTruncatedDouble( -1.001, 3 ); // prints -1.001
    printTruncatedDouble( -1.0005, 3 ); // prints -1.001 (shound be -1?)
    printTruncatedDouble( -1.0004, 3 ); // prints -1
    printf("\n");
    printTruncatedDouble( 1.0004, 3 ); // prints 1
    printTruncatedDouble( 1.0005, 3 ); // prints 1.001
    printTruncatedDouble( 1.001, 3 ); // prints 1.001
    printTruncatedDouble( 1.999, 3 ); // prints 1.999
    printf("\n");
    exit(0);
}

一些高度投票的解决方案建议 printf %g 转换说明符。这是错误的,因为有时%g 会产生科学记数法。其他解决方案使用数学来打印所需的小数位数。

我认为最简单的解决方案是将 sprintf %f 转换说明符一起使用,并从结果中手动删除尾随零和可能的小数点。这是一个C99解决方案:

#include <stdio.h>
#include <stdlib.h>

char*
format_double(double d) {
    int size = snprintf(NULL, 0, "%.3f", d);
    char *str = malloc(size + 1);
    snprintf(str, size + 1, "%.3f", d);

    for (int i = size - 1, end = size; i >= 0; i--) {
        if (str[i] == '0') {
            if (end == i + 1) {
                end = i;
            }
        }
        else if (str[i] == '.') {
            if (end == i + 1) {
                end = i;
            }
            str[end] = '\0';
            break;
        }
    }

    return str;
}

请注意,用于数字和小数点分隔符的字符取决于当前区域设置。上面的代码假定为C或美国英语区域设置。

这是我第一次尝试答案:

void
xprintfloat(char *format, float f)
{
  char s[50];
  char *p;

  sprintf(s, format, f);
  for(p=s; *p; ++p)
    if('.' == *p) {
      while(*++p);
      while('0'==*--p) *p = '\0';
    }
  printf("%s", s);
}

已知错误:可能的缓冲区溢出取决于格式。如果是“。”出现其他原因而不是%f错误的结果可能会发生。

为什么不这样做?

double f = 359.01335;
printf("%g", round(f * 1000.0) / 1000.0);

上面略有变化:

  1. 消除案件的期限(10000.0)。
  2. 处理完第一个句点后中断。
  3. 代码在这里:

    void EliminateTrailingFloatZeros(char *iValue)
    {
      char *p = 0;
      for(p=iValue; *p; ++p) {
        if('.' == *p) {
          while(*++p);
          while('0'==*--p) *p = '\0';
          if(*p == '.') *p = '\0';
          break;
        }
      }
    }
    

    它仍然有溢出的可能,所以要小心; P

由于“.3”,您的代码会舍入到小数点后三位。在f之前

printf("%1.3f", 359.01335);
printf("%1.3f", 359.00999);

因此,如果您将第二行四舍五入到两位小数,则应将其更改为:

printf("%1.3f", 359.01335);
printf("%1.2f", 359.00999);

该代码将输出您想要的结果:

359.013
359.01

*请注意,假设您已经在单独的行上打印,如果没有,则以下内容将阻止它在同一行上打印:

printf("%1.3f\n", 359.01335);
printf("%1.2f\n", 359.00999);

以下程序源代码是我对此答案的测试

#include <cstdio>

int main()
{

    printf("%1.3f\n", 359.01335);
    printf("%1.2f\n", 359.00999);

    while (true){}

    return 0;

}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top