用printf格式化漂浮而不小数如果仅仅尾随0 [英] Use printf to format floats without decimal places if only trailing 0s

查看:359
本文介绍了用printf格式化漂浮而不小数如果仅仅尾随0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能格式化在C浮动只从0用printf显示为2位小数,如果有什么不同?

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

例如:

12 => 12

12.1 => 12.1

12.1 => 12.1

12.12 => 12.12

12.12 => 12.12

我试着使用:

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

但我得到

12 => 12.00

12 => 12.00

12.1 => 12.10

12.1 => 12.10

12.12 => 12.12

12.12 => 12.12

推荐答案

您可以使用%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;
}

结果:


12
12.1
12.12
12.1234

需要注意的是,不同的是˚F格式说明,如果指定先按g 它是指前一个数< STRONG>整个号码的长度(不是小数与˚F)。

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).

这篇关于用printf格式化漂浮而不小数如果仅仅尾随0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆