这不能用普通的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