在C ++使用boost :: lexical_cast的double转换成字符串? [英] Convert double to string using boost::lexical_cast in C++?

查看:117
本文介绍了在C ++使用boost :: lexical_cast的double转换成字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用的lexical_cast 为浮点转换为字符串。通常它工作正常,但我有一些问题与数字无小数点。如何解决在字符串中显示的小数的号码是多少?

I' d like to use lexical_cast to 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?

例如:

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

结果数是 5 ,我需要数 5.00

推荐答案

从文档的升压lexical_cast的

对于更复杂的转换,例如在precision或格式需要比由lexical_cast的默认行为提供了更严格的控制,建议常规的stringstream的做法。当转换是数字到数字,numeric_cast可以提供比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.

例如:

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

这篇关于在C ++使用boost :: lexical_cast的double转换成字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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