且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用固定点符号将double转换为字符串,没有尾随零和witout sprintf

更新时间:2023-11-08 17:09:16

首先计算十进制之前和之后有多少位数:

First you calculate how many potential digits you have before and after the decimal:

int digits_before = 1 + (int)floor(log10(fabs(value)));
int digits_after = std::numeric_limits<double>::digits10 - digits_before;

然后你会发现这些数字中有多少是零:

Then you find out how many of those digits are zeros:

double whole = floor(pow(10, digits_after) * fabs(value) + 0.5);
while (digits_after > 0 && (whole/10.0 - floor(whole/10.0)) < 0.05)
{
    --digits_after;
    whole = floor(whole / 10.0 + 0.5);
}
if (digits_after < 0) digits_after = 0;

现在,您可以使用 std :: setprecision

Now you have a value you can use with std::setprecision:

std::stringstream ss;
ss << std::fixed << std::setprecision(digits_after) << value;

最终这是很多工作和重复的字符串转换的努力,一般只是转换为字符串并删除尾随零。没有,没有简单的格式化选项来做到这一点,你必须以硬的方式或根本不做。

Ultimately this is a lot of work and duplicates effort that the string conversion does anyway, which is why people generally just convert to a string and remove the trailing zeros. And no, there's no simple formatting option to do this, you have to do it the hard way or not at all.

查看上述代码在操作: http://ideone.com/HAk55Y

See the above code in action: http://ideone.com/HAk55Y