Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

c - Use printf to format floats without decimal places if only trailing 0s

Is it possible to format a float in C to only show up to 2 decimal places if different from 0s using printf?

Ex:

12 => 12

12.1 => 12.1

12.12 => 12.12

I tried using:

float f = 12;
printf("%.2f", f)

but I get

12 => 12.00

12.1 => 12.10

12.12 => 12.12

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the %g format specifier:

#include <stdio.h>

int main() {
  float f1 = 12;
  float f2 = 12.1;
  float f3 = 12.12;
  float f4 = 12.1234;
  printf("%g
", f1);
  printf("%g
", f2);
  printf("%g
", f3);
  printf("%g
", f4);
  return 0;
}

Result:

12
12.1
12.12
12.1234

Note that, unlike the f format specifier, if you specify a number before the g it refers to the length of the entire number (not the number of decimal places as with f).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...