简体   繁体   中英

Control the Precision of float number in a string - C++

I'm trying to control the number of Digits i add in a String , but I couldn't control it since i am printing an Array of Strings .

float loads[n] = { 1,2,3,0.05,1,2,3,0.5,1,2,3,3,1,2 };
string print[nBits] = { "" };
int n=14;
int BB;
.
.
.
void main(){
 for (int j = 0; j < nBits; ++j)// 2^n
   {     
         for (int i = 0; i < n; ++i) // n
        {
            BB = arr[j][i];
            R = loads[i];
            if (BB == 1) {
            print[j]+="" +std::to_string(loads[i])+"//";
        }
   }
}

But i eventually get an Array of strings that Looks like this :

0.050000//3.000000//...

Is there any way to control the Precision of the floating number before adding it to the String ?

(so i can have a resulting string control a fixed number of Digits instead)

0.05//3.00// ...

Use std::stringstream together with std::fixed and std::setprecision(n) .

http://en.cppreference.com/w/cpp/io/manip

You can use the standard streaming mechanic:

streams

You can use ostream to generate the string:

#include <ostream>
#include <sstream>
#include <iomanip>

std::ostringstream stream;
for(...) {
   stream << loads[i] << "//";
}
std::string str =  stream.str();

The idea is to generate a stream that you can stream strings too. You can then generate a std::string out of it, using stream.str() . Streams have default values for how to convert numbers. You can influence this with std::setprecision and std::fixed as well as other variables (for more info, see the C++ stdlib reference ).

Using std::setprecision and std::fixed .

std::ostringstream stream;
// set the precision of the stream to 2 and say we want fixed decimals, not
// scientific or other representations.
stream << std::setprecision(2) << std::fixed;

for(...) {
   stream << loads[i] << "//";
}
std::string str =  stream.str();

You find another example here .

sprintf

You can always go the C way and use sprintf although it's discouraged as you have to provide a buffer of correct length, eg:

char buf[50];
if (snprintf(buf, 50, "%.2f", loads[i]) > 0) {
   std::string s(buf);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM