I have a string: (66)
Then I convert it to double and do some math: atof(t.c_str()) / 30
then I convert it back to string: string s = boost::lexical_cast<string>(hizdegerd)
Problem is when I show it on label it becomes 2,20000001.
I've tried everything. sprintf etc.
I want to show only one digit after point.
hizdegerd = atof(t.c_str()) / 30;
char buffer [50];
hizdegerd=sprintf (buffer, "%2.2f",hizdegerd);
if(oncekideger != hizdegerd)
{
txtOyunHiz->SetValue(hizdegerd);
oncekideger = hizdegerd;
}
I think I'd wrap the formatting up into a function template, something like this:
#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";
}
You can use this way of conversion back to string and then only the wished number of digits for the precision will be taken in consideration:
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();
Since you wrote "I want to show":
#include<iostream>
#include<iomanip>
int main()
{
std::cout << std::fixed << std::setprecision(1) << 34.2356457;
}
Output:
34.2
By the way, sprintf is buffer-overflow-vulnerable and is not C++ .
Related
I use setprecision & fixed, but I want to cut off trailing zeros, how do I do that for cout?
#include <iostream>
#include<iomanip>
int main()
{
double b = 132.7489;
double a = 49.932;
double e = a + b;
std::cout << std::fixed;
std::cout << std::setprecision(20);
std::cout << e;
}
How do I tell the program to automatically cut off the trailing decimal places for the exact answer like a calculator. Sorry this is my first time here. I'm used to Javascript & I've never had a problem with exact math. I've googled everywhere.
This will do it...
#include <iostream>
using namespace std;
int main()
{
float f = 42.43500000f, f2 = 25.004300;
cout << defaultfloat << f << endl;
cout << defaultfloat << f2 << endl;
return 0;
}
defaultfloat is a format flag defined in the std namespace.
If printing is your only concern you could use printf and %g format.
As by default six significant digits are printed ,you could use long enough numeric width like .10.
printf("%.10g",e);
So:
#include <iostream>
#include<cstdio>
int main()
{
double b = 132.7489;
double a = 49.932;
double e = a + b;
printf("%.10g",e);
}
I have a string that is in the format #########s###.##
where #### is just a few numbers, and the second piece is usually a decimal, but not always.
I need to break the two number pieces apart, and set them as two doubles(or some other valid number type.
I can only use standard methods for this, as the server it's being run on only has standard modules.
I can currently grab the second piece using find and substr, but can't figure out how to get the first piece. I still haven't done anything that changes the second piece into a numerical type, but hopefully that is much easier.
here's what I have:
string symbol,pieces;
fin >> pieces; //pieces is a string of the type i mentioned #####s###.##
unsigned pos;
pos = pieces.find("s");
string capitals = pieces.substr(pos+1);
cout << "Price of stock " << symbol << " is " << capitals << endl;
istringstream makes it easy.
#include <iostream>
#include <sstream>
#include <string>
int main(int argc, char* argv[]) {
std::string input("123456789s123.45");
std::istringstream output(input);
double part1;
double part2;
output >> part1;
char c;
// Throw away the "s"
output >> c;
output >> part2;
std::cout << part1 << ", " << part2 << std::endl;
return 0;
}
You can specify a count along with an offset when calling substr:
string first = pieces.substr(0, pos);
string second = pieces.substr(pos + 1);
You can do the same thing as you did for the second part:
unsigned pos;
pos = pieces.find("s");
string firstPart = pieces.substr(0,pos);
This code will split the string as you desire and convert them to double, it could easily be changed to convert to float as well:
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
class BadConversion : public std::runtime_error {
public:
BadConversion(std::string const& s)
: std::runtime_error(s)
{ }
};
inline double convertToDouble(std::string const& s,
bool failIfLeftoverChars = true)
{
std::istringstream i(s);
double x;
char c;
if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
throw BadConversion("convertToDouble(\"" + s + "\")");
return x;
}
int main()
{
std::string symbol,pieces;
std::cin >> pieces; //pieces is a string of the type i mentioned #####s###.##
unsigned pos;
pos = pieces.find("s");
std::string first = pieces.substr(0, pos);
std::string second = pieces.substr(pos + 1);
std::cout << "first: " << first << " second " << second << std::endl;
double d1 = convertToDouble(first), d2 = convertToDouble(second) ;
std::cout << d1 << " " << d2 << std::endl ;
}
Just for reference, I took the conversion code from one of my previous answers.
Grabbing the first piece is easy:
string firstpiece = pieces.substr(0, pos);
As for converting to numeric types, I find sscanf() to be particularly useful for that:
#include <cstdio>
std::string pieces;
fin >> pieces; //pieces is a string of the type i mentioned #####s###.##
double firstpiece = 0.0, capitals = 0.0;
std::sscanf(pieces.c_str() "%lfs%lf", &firstpiece, &capitals);
...
Some poeple will complain that this is not C++-y but this is valid C++
char * in = "1234s23.93";
char * endptr;
double d1 = strtod(in,&endptr);
in = endptr + 1;
double d2 = strtod(in, &endptr);
I'm having trouble converting a string into a double.
My string has been declared using the "string" function, so my string is:
string marks = "";
Now to convert it to a double I found somewhere on the internet to use word.c_str(), and so I did. I called it and used it like this:
doubleMARK = strtod( marks.c_str() );
This is similar to the example I found on the web:
n1=strtod( t1.c_str() );
Apparently, that's how it's done. But of course, it doesn't work. I need another parameter. A pointer I believe? But I'm lost at this point as to what I'm suppose to do. Does it need a place to store the value or something? or what?
I also need to convert this string into a integer which I have not begun researching as to how to do, but once I find out and if I have errors, I will edit this out and post them here.
Was there a reason you're not using std::stod and std::stoi? They are at least 9 levels more powerful than flimsy strtod.
Example
#include <iostream>
#include <string>
int main() {
using namespace std;
string s = "-1";
double d = stod(s);
int i = stoi(s);
cout << s << " " << d << " " << i << endl;
}
Output
-1 -1 -1
If you must use strtod, then just pass NULL as the second parameter. According to cplusplus.com:
If [the second parameter] is not a null pointer, the function also sets the value pointed by endptr to point to the first character after the number.
And it's not required to be non-NULL.
Back in the Bad Old Dark Days of C, I'd do something ugly and unsafe like this:
char sfloat[] = "1.0";
float x;
sscanf (sfloat, "%lf", &x);
In C++, you might instead do something like this:
// REFERENCE: http://www.codeguru.com/forum/showthread.php?t=231054
include <string>
#include <sstream>
#include <iostream>
template <class T>
bool from_string(T& t,
const std::string& s,
std::ios_base& (*f)(std::ios_base&))
{
std::istringstream iss(s);
return !(iss >> f >> t).fail();
}
int main()
{
int i;
float f;
// the third parameter of from_string() should be
// one of std::hex, std::dec or std::oct
if(from_string<int>(i, std::string("ff"), std::hex))
{
std::cout << i << std::endl;
}
else
{
std::cout << "from_string failed" << std::endl;
}
if(from_string<float>(f, std::string("123.456"), std::dec))
{
std::cout << f << std::endl;
}
else
{
std::cout << "from_string failed" << std::endl;
}
return 0;
}
Personally, though, I'd recommend this:
http://bytes.com/topic/c/answers/137731-convert-string-float
There are two ways. C gives you strtod which converts between a char
array and double:
// C-ish:
input2 = strtod(input.c_str(), NULL);
The C++ streams provide nice conversions to and from a variety of
types. The way to use strings with streams is to use a stringstream:
// C++ streams:
double input2;
istringstream in(input);
input >> input2;
We can define a stringTo() function,
#include <string>
#include <sstream>
template <typename T>
T stringTo(const std::string& s) {
T x;
std::istringstream in(s);
in >> x;
return x;
}
Then, use it like
std::cout << stringTo<double>("-3.1e3") << " " << stringTo<int>("4");
I am looking for a simple method to format the following float\double numbers to a CString.
I was hoping to use CString.Format(), but alternatives are welcome as well, as long as it ends up being a CString.
3.45
112.2
To the following format:
00003450
00112200
Notice there should be no decimal point.Can this be done simply, if so how?
#include <iomanip>
#include <iostream>
std::cout << std::setw(8) << std::setfill('0') << int(int(YourNumber)*1000+.5);
should do the trick.
Edit: Added rounding.
Edit: Second int() cast for silencing obscure warnings :-)
f does work.
void f(double a) {
const int a1000 = static_cast<int>(a * 1000 + 0.5);
assert(a1000 < 100000000);
const int b = a1000 + 100000000;
std::stringstream ss;
ss << b;
std::cout << ss.str().c_str() + 1; //remove first 1;
}
int main() {
f(3.45);
f(112.2);
}
CString myString;
myString.Format(_T("%08d"), static_cast<int>(num * 1000.0 + 0.5));
Alternatively:
//...
#include <sstream>
#include <iomanip>
using namespace std;
//...
ostringstream s;
s << setfill('0') << setw(8) << static_cast<int>(num * 1000.0 + 0.5);
CString myString(s.str().c_str());
//...
Refs:
CString::Format
printf
Here's a solution using Boost.Format:
#include <boost/format.hpp>
CString f(double d)
{
return str(boost::format("%1$=08.0f") % (1000*d)).c_str();
}
I would like to know what is the easiest way to convert an int to C++ style string and from C++ style string to int.
edit
Thank you very much. When converting form string to int what happens if I pass a char string ? (ex: "abce").
Thanks & Regards,
Mousey
Probably the easiest is to use operator<< and operator>> with a stringstream (you can initialize a stringstream from a string, and use the stream's .str() member to retrieve a string after writing to it.
Boost has a lexical_cast that makes this particularly easy (though hardly a paragon of efficiency). Normal use would be something like int x = lexical_cast<int>(your_string);
You can change "%x" specifier to "%d" or any other format supported by sprintf. Ensure to appropriately adjust the buffer size 'buf'
int main(){
char buf[sizeof(int)*2 + 1];
int x = 0x12345678;
sprintf(buf, "%x", x);
string str(buf);
int y = atoi(str.c_str());
}
EDIT 2:
int main(){
char buf[sizeof(int)*2 + 1];
int x = 42;
sprintf(buf, "%x", x);
string str(buf);
//int y = atoi(str.c_str());
int y = static_cast<int>(strtol(str.c_str(), NULL, 16));
}
This is to convert string to number.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
int convert_string_to_number(const std::string& st)
{
std::istringstream stringinfo(st);
int num = 0;
stringinfo >> num;
return num;
}
int main()
{
int number = 0;
std::string number_as_string("425");
number = convert_string_to_number(number_as_string);
std::cout << "The number is " << number << std::endl;
std::cout << "Number of digits are " << number_as_string.length() << std::endl;
}
Like wise, the following is to convert number to string.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
std::string convert_number_to_string(const int& number_to_convert)
{
std::ostringstream os;
os << number_to_convert;
return (os.str());
}
int main()
{
int number = 425;
std::string stringafterconversion;
stringafterconversion = convert_number_to_string(number);
std::cout << "After conversion " << stringafterconversion << std::endl;
std::cout << "Number of digits are " << stringafterconversion.length() << std::endl;
}
Use atoi to convert a string to an int. Use a stringstream to convert the other way.