Convert double to string with n decimal places without trailing zeros - c++

1)double d = 1.234567899;
Convert this number to string with 8 decimal places without truncation.
So,expected output is "1.23456789", truncating last 9.
and
2)if d = 1.2345699;
so Solution should not append 0 upto 8th decimal place.expected output "1.2345699".
I have tried many solutions,ended up with stringstream c++ class. 2nd problem is solved but first one still persist.
Is there any way to achieve the output?
Thanks in advance.

If you want to truncate part of the string representation without rounding, you need to do that manually:
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include <limits>
int main()
{
std::stringstream s;
double d = 1.234567899;
// print it into sstream using maximum precision
s << std::fixed << std::setprecision(std::numeric_limits<double>::digits10) << 1.234567899;
std::string res = s.str();
// Now the res contains something like 1.234567899000000
// so truncate 9000000000 by hand
size_t dotIndex = res.find(".");
std::string final_res = res.substr(0, dotIndex + 9);
std::cout << final_res << std::endl;
return 0;
}

Would you be served by first Flooring the double to the required decimals?
If so, have a look at http://www.cplusplus.com/forum/beginner/3600/

Truncating exactly as you want:
sprintf(str, "%1.10f", d);
memset(str+10, 0x00, 1);

Related

how to get all decimal number from string in c++

I'm trying to get value (all decimal number) from a text in c++. But I have a problem and I couldn't solve it
#include "pch.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main()
{
std::ifstream infile("C:\\thefile.txt");
float a, b;
while (infile >> a >> b)
{
// process pair (a,b)
}
std::cout << a << " " << b;
}
thefile.txt:
34.123456789 77.987654321
When I run the above code,
a = 34.1235
b = 77.9877
but I want
a = 34.123456789
b = 77.987654321
what should I do?
EDIT: I don't want to print out of a and b. I just want they get the exact values.net
You can't.
A float can only give you six (ish) decimal significant figures. The values in your file, after conversion from string, cannot be held in a float.
First, you need to switch to double, otherwise you won't even have a variable with the full numerical value.
Then, for output, be careful to specify the precision you want.
Please remain aware of the foibles of floating-point, and consider sticking with strings, depending on what you're doing with this data.
There are two main things i see in your code.
float precision is not enough for you data you need double data type.
you need to set proper cout precision to get your desired output.
This code will work for you.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main()
{
std::ifstream infile("newfile.txt");
double a, b;
std::cout.precision(11);
while (infile >> a >> b)
{
// process pair (a,b)
}
std::cout << a << " " << b;
}
you should read your inputs into a string and then convert them into double (depending on enough precision in float on your computer). you can directly display strings. A possible answer is here.
string word;
openfile >> word;
double lol = atof(word.c_str());

Pugi XML: How to set the precision for float numbers

I use pugi::XML parser and i want to set the precision for the floating point numbers. I have already used the rounding function on the float variable, but while printing with pugi::xml, it is printed with 6 decimal digits.
I use below statement to print value in C++11 :
subNode.append_child(pugi::node_pcdata).set_value(to_string(doubleVal).c_str());
Example:
<value>97.802000</value>
must be printed as
<value>97.802</value>
How can i do that ?
Try this:
#include <iomanip> // setprecision
#include <sstream> // stringstream
std::string toStringPrecision(double input,int n)
{
stringstream stream;
stream << std::fixed << setprecision(n) << input;
return stream.str();
}
Then you call it in:
subNode.append_child(pugi::node_pcdata).set_value(toStringPrecision(doubleVal,3).c_str());

Convert string to double variable which is seperated by a comma(0,07)

In C++ I've got a double variable to be read which is seperated by a comma(0,07).I am first reading it a string from an excel and trying to converting it into a double.
string str = "0,07"; // Actually from Excel.
double number = strtod(str .c_str(), NULL);
double number1 = atof(str .c_str());
cout << number<<endl;
cout <<number1<<endl;
Both of them return 0 as output instead of 0.07. can someone explain me how to convert double to 0.07 instead of 0.
You can define a customized numeric facet (numpunct) for it:
class My_punct : public std::numpunct<char> {
protected:
char do_decimal_point() const {return ',';}//comma
};
and then use a stringstream and locale with it:
stringstream ss("0,07");
locale loc(locale(), new My_punct);
ss.imbue(loc);
double d;
ss >> d;
DEMO
The problem is that the default locale is the "C" (for "Classic"), that uses '.' as decimal separator, while excel use the one of the OS. that is most likely the one of a lain language.
You can either:
ask the originator of the data to export with an english-like locale
set in your program a locale based on std::locale("")(so that your program work with the system locale -admitting they are the same, see http://en.cppreference.com/w/cpp/locale/locale)
set you program with a latin-based locale (IT, or ES, for example)
ignore locales and replace the ","-s in the string with "."-s before try to interpret it as number. (see std::replace)
Would this be fine ?
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str = "0,07"; // Actually from Excel.
int index = str.find(',');
str.replace(index, index+1, '.');
double number = stod(str);
cout << number << endl;
return 0;
}
PS: stod is a c++11 function, but you need to use it instead of stof if you want to keep the double precision. Otherwise number should be a float
You can use:
std::replace(str.begin(), str.end(), ',', '.'); // #include <algorithm>
to replace the comma by a dot before converting.
Working example:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string str = "0,07"; // Actually from Excel.
replace(str.begin(), str.end(), ',', '.');
double number = strtod(str.c_str(), NULL);
double number1 = atof(str.c_str());
cout << number << endl;
cout << number1 << endl;
return 0;
}

Converting a string like "2.12e-6" to a double

Is there a built in function in c++ that can handle converting a string like "2.12e-6" to a double?
strtod()
atof should do the job. This how its input should look like:
A valid floating point number for atof is formed by a succession of:
An optional plus or minus sign
A sequence of digits, optionally containing a decimal-point character
An optional exponent part, which itself consists on an 'e' or 'E' character followed by an optional sign and a sequence of digits.
If you would rather use a c++ method (instead of a c function)
Use streams like all other types:
#include <iostream>
#include <sstream>
#include <string>
#include <iterator>
#include <boost/lexical_cast.hpp>
int main()
{
std::string val = "2.12e-6";
double x;
// convert a string into a double
std::stringstream sval(val);
sval >> x;
// Print the value just to make sure:
std::cout << x << "\n";
double y = boost::lexical_cast<double>(val);
std::cout << y << "\n";
}
boost of course has a convenient short cut boost::lexical_cast<double> Or it is trivial to write your own.

Uncleared Answer of Hexadecimal to decimal conversion

The conversion i wrote of hexadecimal to decimal number is working but get some little bit unexpected result.
Expected result : HEX number "0000000F" and Output is in Decimal "15"
In my case
1] if "0000000F" is HEX value and it's conversion is "1532"
2] if "000000FF" is HEX value and it's conversion is "25532"
I am not sure what part of programming is wrong ? every time I get "32" After any decimal value result. Can Anyone suggest how to fix this issue ?
#include <iostream>
using namespace std ;
#include <sstream>
int wmain() {
while(1)
{
int binNumber ;
unsigned int decimal;
string hexString = "0000000F"; //you may or may not add 0x before
stringstream myStream;
myStream <<hex <<hexString;
myStream >>binNumber;
cout <<binNumber <<decimal;
//return 0;
}
}
If you look at the first parts of your outputs, you will notice that they are correct.
But here:
cout <<binNumber <<decimal;
you're printing decimal immediately afterwards, and it is uninitialised.
Remove it.
(On a related note, don't declare variables that you think you might need at some point in the future. Many bugs lurk down that way.)
// Correct code
#include <iostream>
using namespace std ;
#include <sstream>
int wmain() {
while(1)
{
int binNumber ;
// unsigned int dummy=0;
string hexString = "000000FF"; //you may or may not add 0x before
stringstream myStream;
myStream <<hex <<hexString;
myStream >>binNumber;
cout <<binNumber ;
//return 0;
}
}