2013-07-05 80 views
0

我有一個字符串:(66)C++雙串顯示浮點

然後我將其轉換爲翻一番,做一些數學:​​

然後我將其轉換回字符串:string s = boost::lexical_cast<string>(hizdegerd)

問題是當我在標籤上顯示它變成2,20000001。

我試過了一切。 sprintf等

我想在點後只顯示一個數字。

hizdegerd = atof(t.c_str())/30; 
char buffer [50]; 
hizdegerd=sprintf (buffer, "%2.2f",hizdegerd); 
if(oncekideger != hizdegerd) 
{ 

    txtOyunHiz->SetValue(hizdegerd); 

    oncekideger = hizdegerd; 
} 
+4

閱讀[每個計算機科學家應該知道什麼關於浮點運算](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) –

+2

今天是浮點算術。 – devnull

+0

即使閱讀[this](http://en.wikipedia.org/wiki/Floating_point#Representable_numbers.2C_conversion_and_rounding)可能會有所幫助。 – devnull

回答

1

我想我會換行格式化了成函數模板,像這樣:

#include <iostream> 
#include <sstream> 
#include <iomanip> 

template <class T> 
std::string fmt(T in, int width = 0, int prec = 0) { 
    std::ostringstream s; 
    s << std::setw(width) << std::setprecision(prec) << in; 
    return s.str(); 
} 

int main(){ 
    std::string s = fmt(66.0/30.0, 2, 2); 
    std::cout << s << "\n"; 
} 
0

您可以使用轉換這種方式回到string,然後只的數字爲精密所希望的數量將考慮採取:

ostringstream a; 
a.precision(x); // the number of precision digits will be x-1 
double b = 1.45612356; 
a << b; 
std::string s = a.str(); 
0

既然你寫了「我想顯示」:

#include<iostream> 
#include<iomanip> 

int main() 
{ 
    std::cout << std::fixed << std::setprecision(1) << 34.2356457; 
} 

輸出:

34.2 

順便提一下,sprintf的是緩衝區溢出脆弱並且不是C++。

+0

嗯,'sprintf'絕對是C++,即使你不贊成它。 –

+0

它是C++ 11的一部分嗎? –

+0

是的。你爲什麼會這麼想? –