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

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

问题描述

1) double 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.

if d = 1.2345699;

因此,解决方案不应将0添加到小数点后第8位。预期输出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?

推荐答案

如果要截断字符串表示形式的一部分而不舍入,则需要手动执行:

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;
}

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

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