我想使用lexical_cast
將float轉換爲字符串。通常它工作正常,但我有一些沒有小數的問題。我如何確定字符串中顯示的小數位數?在C++中使用boost :: lexical_cast將double轉換爲字符串?
實施例:
double n=5;
string number;
number = boost::lexical_cast<string>(n);
結果數是5
,我需要數5.00
。
我想使用lexical_cast
將float轉換爲字符串。通常它工作正常,但我有一些沒有小數的問題。我如何確定字符串中顯示的小數位數?在C++中使用boost :: lexical_cast將double轉換爲字符串?
實施例:
double n=5;
string number;
number = boost::lexical_cast<string>(n);
結果數是5
,我需要數5.00
。
對於更復雜的轉換,例如在精密或格式需要比通過的lexical_cast默認行爲提供更嚴格的控制,建議使用常規的stringstream方法。在轉換爲數字到數字的情況下,numeric_cast可能會提供比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;
}
如果需要複雜的格式,使用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();
}
你也可以用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);
}
看一看升壓::格式庫。它將printf的可用性與流的類型安全性相結合。爲了速度,我不知道,但我現在懷疑它真的很重要。
#include <boost/format.hpp>
#include <iostream>
int main()
{
double x = 5.0;
std::cout << boost::str(boost::format("%.2f") % x) << '\n';
}
我想你的意思是snprintf :) – criddell 2011-08-30 22:33:03