是否可以在C中格式化浮点数,如果使用printf与0不同,则最多只能显示2个小数位?
例如:
12 => 12
12.1 => 12.1
12.12 => 12.12
我试过用:
float f = 12;
printf("%.2f", f)
Run Code Online (Sandbox Code Playgroud)
但我明白了
12 => 12.00
12.1 => 12.10
12.12 => 12.12
ber*_*nie 54
您可以使用%g格式说明符:
#include <stdio.h>
int main() {
float f1 = 12;
float f2 = 12.1;
float f3 = 12.12;
float f4 = 12.1234;
printf("%g\n", f1);
printf("%g\n", f2);
printf("%g\n", f3);
printf("%g\n", f4);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
结果:
12 12.1 12.12 12.1234
请注意,与f格式说明符不同,如果指定一个数字,则g它指的是整个数字的长度(而不是小数位数f).
根据我们在上面的答案中的讨论,这里是我的程序,适用于小数点前的任意位数.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
float f1 = 12.13;
float f2 = 12.245;
float f3 = 1242.145;
float f4 = 1214.1;
int i = 0;
char *s1 = (char *)(malloc(sizeof(char) * 20));
char *s2 = (char *)(malloc(sizeof(char) * 20));
sprintf(s1, "%f", f1);
s2 = strchr(s1, '.');
i = s2 - s1;
printf("%.*g\n", (i+2), f1);
sprintf(s1, "%f", f2);
s2 = strchr(s1, '.');
i = s2 - s1;
printf("%.*g\n", (i+2), f2);
sprintf(s1, "%f", f3);
s2 = strchr(s1, '.');
i = s2 - s1;
printf("%.*g\n", (i+2), f3);
sprintf(s1, "%f", f4);
s2 = strchr(s1, '.');
i = s2 - s1;
printf("%.*g\n", (i+2), f4);
free(s1);
free(s2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是输出
12.13
12.24
1242.15
1214.1
Run Code Online (Sandbox Code Playgroud)
对于它的价值,这是一个简单的ObjC实现:
// Usage for Output 1 — 1.23
[NSString stringWithFormat:@"%@ — %@", [self stringWithFloat:1],
[self stringWithFloat:1.234];
// Checks if it's an int and if not displays 2 decimals.
+ (NSString*)stringWithFloat:(CGFloat)_float
{
NSString *format = (NSInteger)_float == _float ? @"%.0f" : @"%.2f";
return [NSString stringWithFormat:format, _float];
}
Run Code Online (Sandbox Code Playgroud)
%g不是为我做的 - 这一个是:-)希望它对你们有些人有用.
| 归档时间: |
|
| 查看次数: |
61671 次 |
| 最近记录: |