我一直在寻找 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);
morphNumericString
(或在结束时调用,nDecimals
但在这种情况下,我可能只是将两者合并为一个函数),你最终得到:
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
不返回字符串。
为什么不这样做呢?
double f = 359.01335;
printf("%g", round(f * 1000.0) / 1000.0);
像这样的东西怎么样(可能有舍入错误和需要调试的负值问题,留给读者练习):
printf("%.0d%.4g\n", (int)f/10, f-((int)f-(int)f%10));
它有点程序化,但至少它不会让你做任何字符串操作。
我在字符串(从最右边开始)搜索1
到9
(ASCII 值49
- 57
)范围内的第一个字符,然后null
(设置为0
)它右边的每个字符 - 见下文:
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;
}
}
一些投票率很高的解决方案建议%g
使用printf
. 这是错误的,因为在某些情况下%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 或美国英语语言环境。
一个简单的解决方案,但它可以完成工作,分配已知的长度和精度,并避免采用指数格式的机会(使用 %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);
}
如果您想要最多 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);
}
我的想法是计算不会导致给定双精度值尾随零的所需"%1.*f"
精度,并将其传递给printf() 中的格式。这甚至可以作为单行来完成:
int main() {
double r=1234.56789;
int precision=3;
printf(L"%1.*f", prec(r, precision), r);
}
int prec(const double& r, int precision)
{
double rPos = (r < 0)? -r : r;
double nkd = fmod(rPos, 1.0); // 0..0.99999999
int i, ex10 = 1;
for (i = 0; i < precision; ++i)
ex10 *= 10;
int nki = (int)(nkd * ex10 + 0.5);
// "Eliminate" trailing zeroes
int requiredPrecision = precision;
for (; requiredPrecision && !(nki % 10); ) {
--requiredPrecision;
nki /= 10;
}
return requiredPrecision;
}
这是另一个%g
解决方案。您应该始终提供“足够宽”的格式精度(默认仅为 6)并对值进行四舍五入。我认为这是一个很好的方法:
double round(const double &value, const double& rounding) {
return rounding!=0 ? floor(value/rounding + 0.5)*rounding : value;
}
printf("%.12g" round(val, 0.001)); // prints up to 3 relevant digits
这是我第一次尝试回答:
空白 xprintfloat(char *format, float f) { 字符 [50]; 字符 *p; sprintf(s, 格式, f); for(p=s; *p; ++p) if('.' == *p) { 而(*++p); while('0'==*--p) *p = '\0'; } printf("%s", s); }
已知错误:可能的缓冲区溢出取决于格式。如果 ”。” 除了 %f 可能发生错误结果之外的其他原因。
以上略有变化:
代码在这里:
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
我会说你应该使用
printf("%.8g",value);
如果您使用"%.6g"
某些数字(例如 32.230210),您将无法获得所需的输出,它应该打印32.23021
但它会打印32.2302
遇到同样的问题,双精度是十进制的 15,浮点精度是十进制的 6,所以我分别为它们写了 2 个函数
#include <stdio.h>
#include <math.h>
#include <string>
#include <string.h>
std::string doublecompactstring(double d)
{
char buf[128] = {0};
if (isnan(d))
return "NAN";
sprintf(buf, "%.15f", d);
// try to remove the trailing zeros
size_t ccLen = strlen(buf);
for(int i=(int)(ccLen -1);i>=0;i--)
{
if (buf[i] == '0')
buf[i] = '\0';
else
break;
}
return buf;
}
std::string floatcompactstring(float d)
{
char buf[128] = {0};
if (isnan(d))
return "NAN";
sprintf(buf, "%.6f", d);
// try to remove the trailing zeros
size_t ccLen = strlen(buf);
for(int i=(int)(ccLen -1);i>=0;i--)
{
if (buf[i] == '0')
buf[i] = '\0';
else
break;
}
return buf;
}
int main(int argc, const char* argv[])
{
double a = 0.000000000000001;
float b = 0.000001f;
printf("a: %s\n", doublecompactstring(a).c_str());
printf("b: %s\n", floatcompactstring(b).c_str());
return 0;
}
输出是
a: 0.000000000000001
b: 0.000001
我需要它,而 paxdiablo 的第一个答案就可以了。但我不需要截断,下面的版本可能会稍微快一点?在“.”之后开始搜索字符串结尾(EOS),只有一个 EOS 位置。
//https://stackoverflow.com/questions/277772/avoid-trailing-zeroes-in-printf
//adapted from paxdiablo (removed truncating)
char StringForDouble[50];
char *PointerInString;
void PrintDouble (double number) {
sprintf(StringForDouble,"%.10f",number); // convert number to string
PointerInString=strchr(&StringForDouble[0],'.'); // find decimal point, if any
if(PointerInString!=NULL) {
PointerInString=strchr(&PointerInString[0],'\0'); // find end of string
do{
PointerInString--;
} while(PointerInString[0]=='0'); // remove trailing zeros
if (PointerInString[0]=='.') { // if all decimals were zeros, remove "."
PointerInString[0]='\0';
} else {
PointerInString[1]='\0'; //otherwise put EOS after the first non zero char
}
}
printf("%s",&StringForDouble[0]);
}
由于 f 之前的“.3”,您的代码四舍五入到小数点后三位
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;
}