在 C++ 中使用 boost::lexical_cast 将双精度转换为字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5016464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:10:49  来源:igfitidea点击:

Convert double to string using boost::lexical_cast in C++?

c++stringboost

提问by perusopersonale

I' d like to use lexical_castto convert a float to a string. Usually it works fine, but I have some problems with numbers without decimal. How can I fix number of decimal shown in the string?

我想用来lexical_cast将浮点数转换为字符串。通常它工作正常,但我对没有小数的数字有一些问题。如何修复字符串中显示的小数位数?

Example:

例子:

double n=5;
string number;
number = boost::lexical_cast<string>(n);

Result number is 5, I need number 5.00.

结果编号是5,我需要编号5.00

回答by Mic

From the documentation for boost lexical_cast:

来自boost lexical_cast的文档:

For more involved conversions, such as where precision or formatting need tighter control than is offered by the default behavior of lexical_cast, the conventional stringstream approach is recommended. Where the conversions are numeric to numeric, numeric_cast may offer more reasonable behavior than lexical_cast.

对于更复杂的转换,例如精度或格式需要比 lexical_cast 的默认行为提供的更严格的控制,建议使用传统的 stringstream 方法。在数字到数字的转换中,numeric_cast 可能提供比 lexical_cast 更合理的行为。

Example:

例子:

#include <sstream>
#include <iomanip>

int main() {
    std::ostringstream ss;
    double x = 5;
    ss << std::fixed << std::setprecision(2);
    ss << x;
    std::string s = ss.str();
    return 0;
}

回答by Etienne Monette

Have a look at boost::format library. It merges the usability of printf with type safety of streams. For speed, I do not know, but I doubt it really matters nowadays.

看看 boost::format 库。它结合了 printf 的可用性和流的类型安全性。至于速度,我不知道,但我怀疑现在它真的很重要。

#include <boost/format.hpp>
#include <iostream>

int main()
{
   double x = 5.0;
   std::cout << boost::str(boost::format("%.2f") % x) << '\n';
}

回答by D.Shawley

If you need complex formatting, use std::ostringstreaminstead. boost::lexical_castis meant for "simple formatting".

如果您需要复杂的格式,请std::ostringstream改用。 boost::lexical_cast用于“简单格式化”

std::string
get_formatted_value(double d) {
    std::ostringstream oss;
    oss.setprecision(3);
    oss.setf(std::ostringstream::showpoint);
    oss << d;
    return oss.str();
}

回答by hidayat

you can also use sprintf, which is faster then ostringstream

您还可以使用 sprintf,它比 ostringstream 更快

#include <cstdio>
#include <string>

using namespace std;

int main()
{
    double n = 5.0;

    char str_tmp[50];
    sprintf(str_tmp, "%.2f", n); 
    string number(str_tmp);
}