printf或iostream如何指定点之后的最大位数 [英] How does printf or iostream specify maximum number of digits after the point

查看:156
本文介绍了printf或iostream如何指定点之后的最大位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在iostream中的 printf iomanip 操作符中的什么格式字符串应该用于打印以下格式的浮点:

What format string in printf or iomanip operator in iostream should I use to print the float in the following format:


  • 125.0 => 125

  • 125.1 => 125.1

  • 125.12312 => 125.12

  • 1.12345 => 1.12

  • 1234.1235 => 1234.12

  • 125.0 => 125
  • 125.1 => 125.1
  • 125.12312 => 125.12
  • 1.12345 => 1.12
  • 1234.1235 => 1234.12

简而言之,在点后最多打印两位数字,但删除所有尾随零。

In short, print at most 2 digits after the point, but remove all trailing zeros.

我试过%。2f 但不工作,因为它打印125.00和125.10前两个情况。

I tried %.2f but doesn't work because it prints 125.00 and 125.10 for the first 2 cases.

推荐答案

看起来我想出了一些简单的工作:

Looks like I figured out some simple work around:

void print(float f) {
  f = floor(f * 100.0f + 0.5f) / 100.0f;
  cout << f;
}

可以解决大多数常见的情况。一个不能解决的事情是f> 10e7,cout将以科学的概念打印f。

would solve most common cases. One thing that can't to solved is f > 10e7, which cout will print f in scientific notion.

这篇关于printf或iostream如何指定点之后的最大位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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