C++ Convert string to float - c++

I am trying to convert a string based number to float. Unfortunately I am getting either the rounded off value or truncated value. How can I fix this.
std::string text = "199102.92";
float v = std::stof(text);
std::cout<<v<<std::endl;
This results in 199103
Even if I use setprecision and fixed then it only affects the output stream but the value passed into the float variable remains 199103. How can i resort this problem.
I have also used stringstream in c++ but results seem to be the same except it just displays off well.
I need to preserve the decimal upto 2 places.
I have used stof,stod, they all do the same thing.
You may assume that I am working with currencies.

I assume that you use std::setprecision and std::fixed incorrectly.
Following works for me:
#include <iostream>
#include <iomanip>
#include <string>
string text = "199102.92";
float v = std::stof(text);
std::cout << std::setprecision(2) << std::fixed << v << std::endl;
The result is 199102.92
Compiler info: g++ 5.4.0, --std=c++11.

Related

Concatenate float with string and round to 2 decimal places

So I have a function below formatted as polymorphic void display(string& outStr). The output from this function should basically be formatted into one large string, which will be saved to the outStr parameter and returned to the calling function.
I have successfully formatted my large string into multiple lines but I would like to round my float value to 2 decimal places but I can't figure out how with the way I'm currently appending my strings. I tried using the round() and ceil() functions as some posts online have suggested, but 6 zeros still appear after each decimal place. I would appreciate some help with this as I've been looking for solutions for a while but none of them have worked.
Additionally, I was wondering if the to_string() function I used to convert my float to a string would compile and execute correctly in C++98? I'm using C++11 but my teacher is using C++98 and I'm extremely worried that it won't compile on her end.
If not, can anyone suggest how else I could achieve the same result of turning a float into a string while still formatting multiple lines into the outStr string parameter and returning it to the function? I am not allowed to change the function's parameters, it must stay as display(string& outStr)
My output is a lot longer and complex but I simplified the example for the sake of getting a short and easy solution.
Again, I would appreciate any help!
#include <iostream>
using namespace std;
#include <string>
#include <sstream>
#include <cmath>
#include "Math.h"
void Math::display(string& outStr){
float numOne = 35;
float numTwo = 33;
string hello = "Hello, your percent is: \n";
outStr.append(hello);
string percent = "Percent: \n";
outStr.append(percent);
float numPercent = ceil(((numOne / numTwo) * 100) * 100.0) / 100.0;
outStr.append(to_string(numPercent));
outStr.append("\n");
}
Output should look like:
Hello, your percent is:
Number:
106.06%
There is no need to do any crazy conversions. Since the function is called display, my guess is that it's actually supposed to display the value instead of just save it to a string.
The following code demonstrates how that can be accomplished by just formatting your printing.
#include <cstdio>
#include <iomanip>
#include <iostream>
int main() {
double percentage = 83.1415926;
std::cout << "Raw: " << percentage << "%\n";
std::cout << "cout: " << std::fixed << std::setprecision(2) << percentage << "%\n";
printf("printf: %.2f\%%\n", percentage); // double up % to print the actual symbol
}
Output is:
Raw: 83.1416%
cout: 83.14%
printf: 83.14%
If the function is as backwards as you describe it, there are two possibilities. You don't understand what's actually required and are giving us a bad explanation (my guess given that function signature), or the assignment itself is pure garbage. As much as SO likes to rag on professors, I find it difficult to believe that what you've described and written is what the professor wants. It makes no sense.
A couple notes: there is nothing polymorhpic about the code you've shown. to_string() exists as of C++11, which is easily seen by looking up the function (Link). There is also a discrepancy between what your code attempts to print versus what your output is, and that's before we even get to the number formatting portion. "Percent" or "Number"?

G++ floating point precision

I have these lines in a C++ program,
auto f = log (FLT_MAX / 4);
printf("%e", f);
cout << f;
The printf result is 8.733654e+1, but cout gives me 87.3365. I checked the 32-bit hex values, they're respectively 0x3f5f94e0 and 0x3f5f94d9, meaning, there seems to be enough precision to represent the value exactly.
Do you know why cout is truncating that floating point value?
Do you know why cout is truncating that floating point value?
Because the default precision C++ streams are set to is 6.
You can change the precision with std::setprecision.
This has nothing to do with g++.
What you should do is this:
#include <limits>
#include <iomanip>
std::cout << std::setprecision(std::numeric_limits<double>::digits10+1) << f;
You can also use long double instead of double to get the maximum precision available.
Documentation
std::setprecision
std::numeric_limits

Reading double from file

For my homework I should read double values from a file and sort them. These are the some of the values. But when read them with my code, when a print it for testing they are written in integer form.
std::ifstream infile (in_File);
double a;
while(infile>>a)
{
std::cout<<a<<std::endl;
}
My doubles are started with 185261.886524 then 237358.956723
And my code print the 185262 then 237359 then so on.
Try adding this at the top of your main():
setlocale(LC_ALL, "C");
This will give your program the "C" locale instead of your local one. I imagine your local one uses "," as a decimal point instead of "." as in your data.
You will need to add #include <clocale> at the top of your file as well.
Edit: then, to get more precision, you can do #include <iomanip> and do this at the top of your program:
std::cout << std::setprecision(20);
setprecision changes how many total digits are printed.
Your problem is not the input, but the output: cout by default prints 6 digits of a double, this is why you see the rounded value 185262, not 185261 as you would expect from incorrect input. Use std::setprecision to increase output precision.
This can happen if on your system your localization settings have a different decimal separator than .. Try add the following include:
#include <locale>
and then use the imbue method:
std::ifstream infile (in_File);
infile.imbue(std::locale("C"));
double a;
while(infile>>a)
{
std::cout<<a<<std::endl;
}

Issue when "fixed" stream manipulator is removed

I am new to C++, learning it by my self, and I am using the book "C++ how to program - 7th edition" from Deitel. Now, please have a look at the following code
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
double principle = 1000;
double amount;
double rate = 0.05;
cout << "Year" << setw(21) << "Amount on deposit" << endl;
cout << fixed << setprecision(2);
for(int years=1; years<=10; years++)
{
amount = principle * pow(1.0+rate,1.0);
cout << setw(4) << years << setw(21) << amount << endl;
}
}
When I removed the "fixed" stream manipulator, the output becomes stupid, which means, just ascii letters and numbers. When I insert it, the output comes without any problem. My question is, why is this happening? Is "fixed" mandatory for all the programs which has "double" type outputs? Please help.
And another thing. What are stream manipulators? As a Java developer, I thought these might be some kind of constant variables, but it is not! They are methods? Then why the brackets are not there? Please answer to this question too.
Thanks
The output does not "become stupid": you simply let your output stream choose the format for your floating-point numbers, and it picks scientific notation. This gives you 1e+03 (which means 1*10^3) instead of 1050.00. The use of fixed tells the stream that you do not want scientific notation; you could also use scientific to force the scientific format. Since the precise format depends depends on your application requirements, the choice to use fixed or scientific is ultimately up to you.
Manipulators like fixed are functions, but if you wanted the common () for it then it would look like this:
fixed(cout); //Instead of using the << or >> you pass the stream into the manipulator function.
See this reference for more on manipulators:
http://www.cplusplus.com/reference/iostream/manipulators/
Also, fixed documentation can be found here:
http://www.cplusplus.com/reference/iostream/manipulators/fixed/
Hope this helps
It's not just ascii letter and numbers
1e+03 is scientific writing for 1*10^3 which is 1000
for reference:
http://www.cplusplus.com/reference/iostream/manipulators/fixed/
If you had chose a wider precision, your output would have been different without fixed.
cout << setprecision(6); // 6 instead of 2
Then your output would have looked more like you expected. (Incidentally, you should compute the compound interest by folding the interest earned back into the principle.)
Otherwise, with only setprecision(2), the formatter decides to use scientific notation in order to only display 2 digits of precision.
But, since you want the output to provide a fixed number of digits, what you have provided (both fixed and setprecision(2)) will do that.

Only 2 digits in exponent in scientific ofstream

So according to cplusplus.com when you set the format flag of an output stream to scientific notation via
of.setf(ios::scientific)
you should see 3 digits plus and a sign in the exponent. However, I only seem to get 2 in my output. Any ideas? Compiled on Mac OS using GCC 4.0.1.
Here's the actual code I am using:
of.setf(ios::scientific);
of.precision(6);
for (int i=0;i<dims[0];++i) {
for (int j=0;j<dims[1];++j) {
of << setw(15) << data[i*dims[1]+j];
}
of << endl;
}
and an example line of output:
1.015037e+00 1.015037e+00 1.395640e-06 -1.119544e-06 -8.333264e-07
Thanks
I believe cplusplus.com is incorrect, or at least is documenting a particular implementation - I can't see any other online docs which specifically state the number of exponent digits which are displayed - I can't even find it in the C++ specification.
Edit:
The C++ Standard Library: A Tutorial and Reference doesn't explicitly state the number of exponent digits; but all it's examples display two exponent digits.
It's implementation specific.
This is a bug in M$ implementation AFAIK
http://groups.google.com/group/comp.lang.c++/browse_thread/thread/624b679a4faf03d
I'm getting 3 in MSVC++08 and g++ 4.4.0 with this code:
#include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <vector>
typedef float NumberType;
double generate_number(void)
{
return static_cast<NumberType>(std::rand()) / RAND_MAX;
}
void print_number(NumberType d)
{
std::cout << std::setw(15) << d << std::endl;
};
int main(void)
{
std::vector<NumberType> data;
std::generate_n(std::back_inserter(data), 10, generate_number);
// print
std::cout.setf(std::ios::scientific);
std::cout.precision(6);
std::for_each(data.begin(), data.end(), print_number);
}
You can easily change the number type it uses. It gives me three places with both float and double, and the standard says nothing on the actual formatting, so I'd go with mgb's answer.
I have just had a thought - since I am printing floats, why would it display 3 exponent values since the max/min exponent is ~38. I bet if the data array were type double there would be 3.