I have been trying to convert a double into string without the C++11 (ToString) but it only accepts the number of decimals to be 5 as default. How can I change that?
The command is:
string a = static_cast<ostringstream*>( &(ostringstream()<<digits) )->str();
but it keeps 5 decimals while I want to create a string which has all the decimals (e.g. 100)
I know that, that many decimals dont matter. This is one point of the exercise I was doing.
Any suggestions?
Thank you very much for your time
Cheers!
Use IO manipulators setprecision here on std::cout but works on stringstream:
// setprecision example from cplusplus.com
#include <iostream> // std::cout, std::fixed
#include <iomanip> // std::setprecision
int main () {
double f =3.14159;
std::cout << std::fixed << std::setprecision(9) << f << '\n';
return 0;
}
By the way, no double will have 100 meaningfull digit, it's 15 or 17, I forgot exactly how many.
EDIT: I forgot, if you can use C++11... You can (and should) use to_string
#include <string>
// ....
std::string f_str = std::to_string(f);
This worked for me finally
digits = 1.12345123451234;
char buff[100];
sprintf(buff, "%1.14f", digits);
string a(buff);
Thanks for checking it in any case
Cheers
Related
How do you convert a float to a string in C++ while specifying the precision & number of decimal digits?
For example: 3.14159265359 -> "3.14"
A typical way would be to use stringstream:
#include <iomanip>
#include <sstream>
double pi = 3.14159265359;
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << pi;
std::string s = stream.str();
See fixed
Use fixed floating-point notation
Sets the floatfield format flag for the str stream to fixed.
When floatfield is set to fixed, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part.
and setprecision.
For conversions of technical purpose, like storing data in XML or JSON file, C++17 defines to_chars family of functions.
Assuming a compliant compiler (which we lack at the time of writing),
something like this can be considered:
#include <array>
#include <charconv>
double pi = 3.14159265359;
std::array<char, 128> buffer;
auto [ptr, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), pi,
std::chars_format::fixed, 2);
if (ec == std::errc{}) {
std::string s(buffer.data(), ptr);
// ....
}
else {
// error handling
}
The customary method for doing this sort of thing is to "print to string". In C++ that means using std::stringstream something like:
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << number;
std::string mystring = ss.str();
You can use C++20 std::format:
#include <format>
int main() {
std::string s = std::format("{:.2f}", 3.14159265359); // s == "3.14"
}
or the fmt::format function from the {fmt} library, std::format is based on (godbolt):
#include <fmt/core.h>
int main() {
std::string s = fmt::format("{:.2f}", 3.14159265359); // s == "3.14"
}
where 2 is a precision.
It is not only shorter than using iostreams or sprintf but also significantly faster and is not affected by the locale.
Another option is snprintf:
double pi = 3.1415926;
std::string s(16, '\0');
auto written = std::snprintf(&s[0], s.size(), "%.2f", pi);
s.resize(written);
Demo. Error handling should be added, i.e. checking for written < 0.
Here a solution using only std. However, note that this only rounds down.
float number = 3.14159;
std::string num_text = std::to_string(number);
std::string rounded = num_text.substr(0, num_text.find(".")+3);
For rounded it yields:
3.14
The code converts the whole float to string, but cuts all characters 2 chars after the "."
Here I am providing a negative example where your want to avoid when converting floating number to strings.
float num=99.463;
float tmp1=round(num*1000);
float tmp2=tmp1/1000;
cout << tmp1 << " " << tmp2 << " " << to_string(tmp2) << endl;
You get
99463 99.463 99.462997
Note: the num variable can be any value close to 99.463, you will get the same print out. The point is to avoid the convenient c++11 "to_string" function. It took me a while to get out this trap. The best way is the stringstream and sprintf methods (C language). C++11 or newer should provided a second parameter as the number of digits after the floating point to show. Right now the default is 6. I am positing this so that others won't wast time on this subject.
I wrote my first version, please let me know if you find any bug that needs to be fixed. You can control the exact behavior with the iomanipulator. My function is for showing the number of digits after the decimal point.
string ftos(float f, int nd) {
ostringstream ostr;
int tens = stoi("1" + string(nd, '0'));
ostr << round(f*tens)/tens;
return ostr.str();
}
how to print specific number of digits in c++?For example ,printing 8 digits totally(before and after decimal point combined)
Edit: For further clarification, setprecision sets the digits when i have decimal digits to display.I want to display integer 30 also as 30.000000 ,in 8 digits.
The setprecision command puts fixed no. of digits after decimal and i don't want that.
In short , I want an alternative of c command printf("%8d",N) in C++.
You can do it using setprecision() function from include iomanip and fixed like:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double d = 1000;
double t = d;
int dc=0;
while(t>0.9)
{
dc++;
t= t/10;
}
cout<<"dc:"<<dc<<endl;
cout << fixed;
std::cout << std::setprecision(dc);
std::cout << d;
return 0;
}
The setprecision() will not work fine every time So you have to use fixed as well.
You should use the c++ header iomanip what you want is the setprecision() function:
std::cout << std::setprecision(5) << 12.3456789 << std::endl;
outputs 12.346. It also has other modifiers you can find here
EDIT
If you want to print trailing 0s, you need to also use std::fixed. This says to use that number of digits, regardless of whether or not they are significant. If you want that to be the total number, you could figure out the size of the number, then change the precision you set it to based on that, so something like:
#include <iostream>
#include <iomanip>
#include <cmath>
int main()
{
double input = 30;
int magnitude = 0;
while(input / pow(10, magnitude))
{
++magnitude;
}
std::cout << std::fixed << std::setprecision(8 - magnitude) << input << std::endl;
return 0;
}
This returns 30.000000. You can also do something similar by outputting to a string, then displaying that string.
How do you convert a float to a string in C++ while specifying the precision & number of decimal digits?
For example: 3.14159265359 -> "3.14"
A typical way would be to use stringstream:
#include <iomanip>
#include <sstream>
double pi = 3.14159265359;
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << pi;
std::string s = stream.str();
See fixed
Use fixed floating-point notation
Sets the floatfield format flag for the str stream to fixed.
When floatfield is set to fixed, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part.
and setprecision.
For conversions of technical purpose, like storing data in XML or JSON file, C++17 defines to_chars family of functions.
Assuming a compliant compiler (which we lack at the time of writing),
something like this can be considered:
#include <array>
#include <charconv>
double pi = 3.14159265359;
std::array<char, 128> buffer;
auto [ptr, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), pi,
std::chars_format::fixed, 2);
if (ec == std::errc{}) {
std::string s(buffer.data(), ptr);
// ....
}
else {
// error handling
}
The customary method for doing this sort of thing is to "print to string". In C++ that means using std::stringstream something like:
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << number;
std::string mystring = ss.str();
You can use C++20 std::format:
#include <format>
int main() {
std::string s = std::format("{:.2f}", 3.14159265359); // s == "3.14"
}
or the fmt::format function from the {fmt} library, std::format is based on (godbolt):
#include <fmt/core.h>
int main() {
std::string s = fmt::format("{:.2f}", 3.14159265359); // s == "3.14"
}
where 2 is a precision.
It is not only shorter than using iostreams or sprintf but also significantly faster and is not affected by the locale.
Another option is snprintf:
double pi = 3.1415926;
std::string s(16, '\0');
auto written = std::snprintf(&s[0], s.size(), "%.2f", pi);
s.resize(written);
Demo. Error handling should be added, i.e. checking for written < 0.
Here a solution using only std. However, note that this only rounds down.
float number = 3.14159;
std::string num_text = std::to_string(number);
std::string rounded = num_text.substr(0, num_text.find(".")+3);
For rounded it yields:
3.14
The code converts the whole float to string, but cuts all characters 2 chars after the "."
Here I am providing a negative example where your want to avoid when converting floating number to strings.
float num=99.463;
float tmp1=round(num*1000);
float tmp2=tmp1/1000;
cout << tmp1 << " " << tmp2 << " " << to_string(tmp2) << endl;
You get
99463 99.463 99.462997
Note: the num variable can be any value close to 99.463, you will get the same print out. The point is to avoid the convenient c++11 "to_string" function. It took me a while to get out this trap. The best way is the stringstream and sprintf methods (C language). C++11 or newer should provided a second parameter as the number of digits after the floating point to show. Right now the default is 6. I am positing this so that others won't wast time on this subject.
I wrote my first version, please let me know if you find any bug that needs to be fixed. You can control the exact behavior with the iomanipulator. My function is for showing the number of digits after the decimal point.
string ftos(float f, int nd) {
ostringstream ostr;
int tens = stoi("1" + string(nd, '0'));
ostr << round(f*tens)/tens;
return ostr.str();
}
I have a number of type double. I want to get a part of it. For example,
If the number is 13041004236.980835 I want my program to remove first 4 digits and return 1004236.980835
What is the shortest way to do this in c++?
Thanks!
#include <string>
#include <sstream>
std::stringstream ss;
ss << number;
std::string str = ss.str();
str.erase( 0, 4 );
Here's how to do it with math:
auto digits = floor(log10(number)) + 1;
number = fmod(number, pow(10, digits - 4));
You can use the string stream approach from the other answer as well, but you need to use
ss << std::fixed << std::setprecision(std::numeric_limits<double>::digits10);
To not lose precision (assuming you're using a double).
Convert it into a string, shorten it and convert it back.
I'm trying to convert a double number to a std::string, the conversion should print either in the decimal format with 2 decimal digits or in the exponential form:
1 -> 1.00
0.1 -> 0.10
0.01 -> 0.01
0.015 -> 1.5e-2
10 -> 10.00
100 -> 100.00
15000 -> 1.5e4
I tried to use the boost::format function with the %g type, but while it is possible to set the number of significant digits, it's not possible to set the number of printed digits after the decimal point:
1 -> 1
0.1 -> 0.1
0.01 -> 0.01
10 -> 10
100 -> 100
Is there a better way of doing this kind of conversion/formatting? I would preferably use the Standard Library or Boost.
Choose scientific or fixed depending on the size of the number.
It's that easy.
Cheers & hth.,
No boost needed although there should be a way to do this with boost::format or sprintf if you want.
#include <iostream>
#include <iomanip>
int main()
{
std::string numStr("3.14159265");
double num(atof(numStr.c_str()));
std::cout
<< std::setprecision(2)
<< std::scientific << num
<< std::fixed << num;
return 0;
}
Edit: Misread the question if you want to go from double to std::string I'd use a std::ostringstream which supports the same iostream manipulators and insertion operator. Then you can call str() to get a string out of it.
You can use ostringstream, like so
#include <sstream>
#include <string>
std::string FloatToString(float fNumber)
{
std::ostringstream os;
os << fNumber;
return os.str();
}
I'm not sure if this is what you are looking for but...
You can control the number of printed digits using cout with using the setprecision function.
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
double d = 123123.23234234;
cout << setprecision(15) << d;
system("pause");
return 0;
}
sprintf() ; should be easy to help you print double into a string/char array .
Plain old C sprintf supports # of decimals like so: "%.3g"
You can turn the char* output into a std::string easily enough.