c++boost格式float-如何指定我不想要的.以及后面的零

c++ boost format float - how to specify that I do not want . and following zeros

本文关键字:float- 格式 何指定 我不想 c++boost      更新时间:2023-10-16

我想使用boost::format将浮点数转换为字符串。以下是预期结果的几个例子:

0.5     -> "0.5"
0       -> "0"
1.00001 -> "1"
3.66    -> "3.7"

我目前正在使用

boost::format("%1$.1f")

它基本上是有效的,但当我想要"0""1"时,0的结果是"0.0"1.00001"1.0"

为了摆脱毫无意义的.0,我需要更改什么?

使用条件在两种格式之间进行选择。

boost::format(abs(x-floor(x+0.05)) < 0.1 ? "%1$.0f" : "%1$.1f")