双转换为字符串有n位小数不尾随零 [英] Convert double to string with n decimal places without trailing zeros

查看:93
本文介绍了双转换为字符串有n位小数不尾随零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1)双D = 1.234567899; 结果
转换这一数字字符串8位小数不截断。
因此,预期成果是1.23456789,截短最后9。

1)double d = 1.234567899;
Convert this number to string with 8 decimal places without truncation. So,expected output is "1.23456789", truncating last 9.

2)如果d = 1.2345699; 结果
所以解决方案应该没有超出place.expected 8小数0追加输出1.2345699。

2)if d = 1.2345699;
so Solution should not append 0 upto 8th decimal place.expected output "1.2345699".

我已经尝试了多种解决方案,结束了stringstream的C ++类。第二个问题是解决了,但是第一个仍然存在。

I have tried many solutions,ended up with stringstream c++ class. 2nd problem is solved but first one still persist.

有什么办法来实现输出?

Is there any way to achieve the output?

先谢谢了。

推荐答案

如果要截断字符串重新presentation的一部分,无需四舍五入,你需要做的是手动:

If you want to truncate part of the string representation without rounding, you need to do that manually:

#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include <limits>

int main()
{
        std::stringstream s;
        double d = 1.234567899;

        // print it into sstream using maximum precision
        s << std::fixed << std::setprecision(std::numeric_limits<double>::digits10) << 1.234567899;
        std::string res = s.str();

        // Now the res contains something like 1.234567899000000
        // so truncate 9000000000 by hand

        size_t dotIndex = res.find(".");

        std::string final_res = res.substr(0, dotIndex + 9);

        std::cout << final_res << std::endl;

        return 0;
}

这篇关于双转换为字符串有n位小数不尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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