使用固定点符号将double转换为字符串,没有尾随零和witout sprintf [英] Convert double to string with fixed point notation, no trailing zeroes and witout sprintf

查看:92
本文介绍了使用固定点符号将double转换为字符串,没有尾随零和witout sprintf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题已被问过几次,但所有答案都涉及sprintf或涉及手动删除尾部零。真的没有更好的方法吗?是不可能实现这个与 std :: stringstream

This question has been asked a couple of times, but all the answers either refer to sprintf or involve deleting the trailing zeroes manually. Is there really no better way? is it not possible to achieve this with std::stringstream?

推荐答案

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

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

这篇关于使用固定点符号将double转换为字符串,没有尾随零和witout sprintf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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