Float zu String mit vorgegebener Formatierung
-
Hallo Leute,
ich möchte ein float in einen String umwandeln, nur soll sich der string mittels eines Fromats (auch ein string) konfigurieren lassen.
z.B.:
Float___________Format__________Ergebnis (std::string)
1.1_____________0.00____________1.10
1.1__________000.000____________001.100
123.456__________0.0____________123.5
1e3_____________0.0____________1000.0wichtig wäre auch noch das bei der Funktion im String keine Exponentialschreibweise steht, also das auch 1000.0 nicht 1e4 wird.
Versucht hab ichs mit sprintf, iomanip mit stringstrams und boost::format aber ich bekomms mit den Funtkionen leider einfach nicht so hin.
Kennt jemand eine Funktion mit der ich weiterkomme oder hat ein paar Tipps wie ich das am besten Löse?Danke!
-
#include <iomanip> #include <string> #include <sstream> #include <iostream> using std::string; int main() { std::ostringstream stream; size_t anzahl_kommastellen(2); float deine_fliesskommazahl(1.456); stream << deine_fliesskommazahl << string(10,'_') << "0." << string(anzahl_kommastellen,'0') << string(10,'_') << std::fixed << std::setprecision(anzahl_kommastellen) << deine_fliesskommazahl; std::cout << stream.str(); // Der String }
Ein Ansatz.
-
boost::format
-
@Hacker
Vielen Dank!! Auf den Code kann ich super aufbauen@Maxi
Wiegesagt mit boost::format hab ichs nicht zusammengebracht.
-
#include <iostream> #include <iomanip> #include <string> #include <sstream> struct Foo { float zahl; std::string format; }; int main() { using namespace std; Foo output[] = { {1.1f, "0.00"}, {-1.1f, "000.000" }, {123.456f, "0.0" }, {1e3f, "0.0" }, }; // 12345678901234567890123456789 cout << " Float Format Ergebnis" << endl; for( size_t i = 0; i < sizeof(output)/sizeof(*output); ++i ) { const string format = output[i].format; const float zahl = output[i].zahl; cout << setw(8) << zahl << " " << setw(8) << right << format << " "; ostringstream out; // -- hier ist jetzt die formatierte Ausagbe out << fixed << setprecision( format.size() - format.rfind('.') - 1 ) << setfill('0') << showpoint << internal << setw(format.size()) << zahl; cout << out.str() << endl; } return 0; }
eine Lösung
Ausgabe:
Float Format Ergebnis 1.1 0.00 1.10 -1.1 000.000 -01.100 123.456 0.0 123.5 1000 0.0 1000.0
Gruß
Werner
-
@Werner
1000 Dank!!So einfach kanns sein wenn man weiß wie.
Danke an alle für die schnelle und tolle Hifle!