I have already read throw the suggestions on Converting Double to String in C++ and
Convert double to string C++?
but I have been asked to create a function non-OOP to take in a double, and return a std::string using only math. I have been able to do this with an int in the past wich:
std::string toString(int value) {
string result = "";
bool negative = false;
if ( value < 0 ) {
negative = true;
value *= (-1);
}
do {
string tmpstr = "0";
tmpstr[0] += value%10;
result = tmpstr + result;
value /= 10;
} while ( value != 0);
if ( negative ) {
result = "-" + result;
}
return result;
}
but the problem is that it uses a check for greater then zero to keep going. I keep thinking something like
if ( value < 0 ){
value *= 10;
}
I thing that this should go before the %10 but I’m not sure. every time I try I get a whole number, and not the decimal.
for example I give it 125.5 (result of 251/2), and it outputs 1255. though in some cases I only get 125. any help would be great.
Update:chosen solution
std::string toString(float value){
bool negative = false;
if ( value < 0 ) {
negative = true;
value *= (-1);
}
int v1 = value; // get the whole part
value -= v1; // get the decimal/fractional part
//convert and keep the whole number part
std::string str1 = toString(v1);
std::string result = "";
do {
value *= 10;
int tmpint = value;
value -= tmpint;
string tmpstr = "0";
tmpstr[0] += tmpint % 10;
result = tmpstr + result;
value /= 10;
} while ( value != 0);
result = str1 + "." + result;
if ( negative ) {
result = "-" + result;
}
return result;
}
Do you have to use math, can’t you use anostringstream?Otherwise you can do it in two parts:
To get the integer part, just cast the value to an
int. To get the fraction part by itself, subtract the integer part from value.When you have the fractions, multiply by ten and get the that value as an integer, which will be a single-digit integer.
Edit: Added code sample
Note: The above function exposes some of the problems floating point numbers have on computers. For example, the value
1.234becomes the string"1.2339999999999999857891452847979962825775146484375".