472,958 Members | 2,187 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,958 software developers and data experts.

Need help converting a string to a float...

I'm having this weird problem where my code does the following
conversion from string to float:

27000000.0 -27000000.00
2973999.99 -29740000.00
2989999.13 -2989999.25

The number on the left is the string I get after tokenizing a bigger
string. The number on the right is the number I get after the conversion.

I've tried two different ways of converting, one way the older C way
using atof, and another more C++ way. Either way, I get the same
result. Can anyone shed some light on this for me?

Here's the code:

string token;
string tokens[14];
stringstream iss;
getline(fin,bfr);
while (getline(fin, bfr))
{
iss << bfr;
i = 0;
while (getline(iss, token, ','))
{
tokens[i++] = token;
}

std::istringstream b(tokens[0]);
b >price;

//price = atof(tokens[0].c_str());
Jun 7 '07 #1
10 3168
On Jun 7, 2:52 pm, Hank Stalica <u...@example.netwrote:
I'm having this weird problem where my code does the following
conversion from string to float:

27000000.0 -27000000.00
2973999.99 -29740000.00
2989999.13 -2989999.25

The number on the left is the string I get after tokenizing a bigger
string. The number on the right is the number I get after the conversion.

I've tried two different ways of converting, one way the older C way
using atof, and another more C++ way. Either way, I get the same
result. Can anyone shed some light on this for me?

Here's the code:

string token;
string tokens[14];
stringstream iss;
getline(fin,bfr);
while (getline(fin, bfr))
{
iss << bfr;
i = 0;
while (getline(iss, token, ','))
{
tokens[i++] = token;
}

std::istringstream b(tokens[0]);
b >price;

//price = atof(tokens[0].c_str());
I don't think conversion is your problem, I think its your method of
outputting your numbers that is causing rounding and confusion...
JMO.
Jun 7 '07 #2
Could be.

Here's code I used to display the numbers side by side:

printf("%s %10.2f\n",tokens[0].c_str(), price);

SpreadTooThin wrote:
On Jun 7, 2:52 pm, Hank Stalica <u...@example.netwrote:
>I'm having this weird problem where my code does the following
conversion from string to float:

27000000.0 -27000000.00
2973999.99 -29740000.00
2989999.13 -2989999.25

The number on the left is the string I get after tokenizing a bigger
string. The number on the right is the number I get after the conversion.

I've tried two different ways of converting, one way the older C way
using atof, and another more C++ way. Either way, I get the same
result. Can anyone shed some light on this for me?

Here's the code:

string token;
string tokens[14];
stringstream iss;
getline(fin,bfr);
while (getline(fin, bfr))
{
iss << bfr;
i = 0;
while (getline(iss, token, ','))
{
tokens[i++] = token;
}

std::istringstream b(tokens[0]);
b >price;

//price = atof(tokens[0].c_str());

I don't think conversion is your problem, I think its your method of
outputting your numbers that is causing rounding and confusion...
JMO.

Jun 7 '07 #3
I used the following code to verify if it was display issue or an actual
conversion issue:

if (price == 2989999.13)
cout << "Match" << endl;

And match was not displayed, so it looks like the conversion is getting
screwed up somehow.

Hank Stalica wrote:
I'm having this weird problem where my code does the following
conversion from string to float:

27000000.0 -27000000.00
2973999.99 -29740000.00
2989999.13 -2989999.25

The number on the left is the string I get after tokenizing a bigger
string. The number on the right is the number I get after the conversion.

I've tried two different ways of converting, one way the older C way
using atof, and another more C++ way. Either way, I get the same
result. Can anyone shed some light on this for me?

Here's the code:

string token;
string tokens[14];
stringstream iss;
getline(fin,bfr);
while (getline(fin, bfr))
{
iss << bfr;
i = 0;
while (getline(iss, token, ','))
{
tokens[i++] = token;
}

std::istringstream b(tokens[0]);
b >price;

//price = atof(tokens[0].c_str());
Jun 7 '07 #4
Hank Stalica wrote:
I'm having this weird problem where my code does the following
conversion from string to float:

27000000.0 -27000000.00
2973999.99 -29740000.00
Is this correct, or is it an extra 0?
2989999.13 -2989999.25
This sounds reasonable. If you know how a float looks like in your memory,
you'd expect this too.
The number on the left is the string I get after tokenizing a bigger
string. The number on the right is the number I get after the conversion.

I've tried two different ways of converting, one way the older C way
using atof, and another more C++ way. Either way, I get the same
result. Can anyone shed some light on this for me?
A float can't just store any number you put in. A float has a limited number
of precise digits. What you see is rounding errors.

#include <iostream>
#include <limits>

int main() {
std::cout << std::numeric_limits<float>::digits10 << "\n";
}

On my machine, this program outputs the number 6, indicating that a float
can store six decimal digits precisely. Your numbers have (except for the
first) more than six decimal digits. The indication is often a little low,
because computers don't use the decimal system.
Here's the code:

string token;
string tokens[14];
stringstream iss;
getline(fin,bfr);
while (getline(fin, bfr))
{
iss << bfr;
i = 0;
while (getline(iss, token, ','))
{
tokens[i++] = token;
}

std::istringstream b(tokens[0]);
b >price;

//price = atof(tokens[0].c_str());
Don't expect floats or doubles to be accurate. And following: Never use
floats or doubles for prices.

--
Robert Bauck Hamar
Jun 7 '07 #5
Did a little bit of unit testing with the following code and got the
same result:

#include <iostream>
using std::cout;
using std::cin;

int main()
{
char s1[] = "2989999.13";
float f = atof(s1);
printf("%12.2f",f);

if (f == 2989999.13)
cout << "Matches";

return 0;
}

It's converting 2989999.13 to 2989999.25.
What's going on?

Hank Stalica wrote:
I'm having this weird problem where my code does the following
conversion from string to float:

27000000.0 -27000000.00
2973999.99 -29740000.00
2989999.13 -2989999.25

The number on the left is the string I get after tokenizing a bigger
string. The number on the right is the number I get after the conversion.

I've tried two different ways of converting, one way the older C way
using atof, and another more C++ way. Either way, I get the same
result. Can anyone shed some light on this for me?

Here's the code:

string token;
string tokens[14];
stringstream iss;
getline(fin,bfr);
while (getline(fin, bfr))
{
iss << bfr;
i = 0;
while (getline(iss, token, ','))
{
tokens[i++] = token;
}

std::istringstream b(tokens[0]);
b >price;

//price = atof(tokens[0].c_str());
Jun 7 '07 #6
Ok, that makes sense.
So I should store the value as two ints? One for the whole number and
one for the fractional amount?

Robert Bauck Hamar wrote:
Hank Stalica wrote:
>I'm having this weird problem where my code does the following
conversion from string to float:

27000000.0 -27000000.00
2973999.99 -29740000.00

Is this correct, or is it an extra 0?
>2989999.13 -2989999.25

This sounds reasonable. If you know how a float looks like in your memory,
you'd expect this too.
>The number on the left is the string I get after tokenizing a bigger
string. The number on the right is the number I get after the conversion.

I've tried two different ways of converting, one way the older C way
using atof, and another more C++ way. Either way, I get the same
result. Can anyone shed some light on this for me?

A float can't just store any number you put in. A float has a limited number
of precise digits. What you see is rounding errors.

#include <iostream>
#include <limits>

int main() {
std::cout << std::numeric_limits<float>::digits10 << "\n";
}

On my machine, this program outputs the number 6, indicating that a float
can store six decimal digits precisely. Your numbers have (except for the
first) more than six decimal digits. The indication is often a little low,
because computers don't use the decimal system.
>Here's the code:

string token;
string tokens[14];
stringstream iss;
getline(fin,bfr);
while (getline(fin, bfr))
{
iss << bfr;
i = 0;
while (getline(iss, token, ','))
{
tokens[i++] = token;
}

std::istringstream b(tokens[0]);
b >price;

//price = atof(tokens[0].c_str());

Don't expect floats or doubles to be accurate. And following: Never use
floats or doubles for prices.
Jun 7 '07 #7
Hank Stalica wrote:
Ok, that makes sense.
So I should store the value as two ints? One for the whole number and
one for the fractional amount?
Depends on what you need. If the fractional part is always a fixed number of
integers, you only need one integer. Just place the decimal separator when
printing and check it on input. Before you pick that solution, you should
assert that integers are big enough for your task. If not, you could use a
library. GMP might suit your needs <URL:http://gmplib.org/>

By the way: When following up, try to insert your text below the relevant
parts in the previous post. Then delete unrelevant parts.
Robert Bauck Hamar wrote:
>A float can't just store any number you put in. A float has a limited
number of precise digits. What you see is rounding errors.
--
Robert Bauck Hamar

Jun 7 '07 #8
Hank Stalica wrote:
Could be.
Please don't top-post. Your replies belong following or interspersed
with properly trimmed quotes. See the majority of other posts in the
newsgroup, or the group FAQ list:
<http://www.parashift.com/c++-faq-lite/how-to-post.html>
Jun 7 '07 #9
Hank,
Please don't top-post in this newsgroup. Your responses belong
interspersed with appropriately trimmed quotes. I have fixed it below.

Hank Stalica <us**@example.netwrote:
Hank Stalica wrote:
>I'm having this weird problem where my code does the following
conversion from string to float:

27000000.0 -27000000.00
2973999.99 -29740000.00
2989999.13 -2989999.25

The number on the left is the string I get after tokenizing a bigger
string. The number on the right is the number I get after the conversion.

Did a little bit of unit testing with the following code and got the
same result:
[code snipped]
>
It's converting 2989999.13 to 2989999.25.
What's going on?
See this entry in the FAQ (and also the surrounding ones):

[29.16] Why is floating point so inaccurate? Why doesn't this print 0.43?
http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.16

Also, you should read this paper by David Goldberg when you have the
time (links given at the end of FAQ #29.17):

What Every Computer Scientist Should Know About Floating-Point Arithmetic

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Jun 7 '07 #10
Thanks for the help, everyone and my apologies for top posting.

I decided to split the float up into two integers and it seems to be
working.

Best Regards,
--Hank Stalica
Jun 8 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Ikot | last post by:
Hello, I am stuck with a problem, might be very trivial, to ask here, but dont find a way out. I read a string like 12345.678 from a text file, which will be string for me, but how do I convert it...
15
by: Bushido Hacks | last post by:
Hey c.l.c++ and/or c.g.a.opengl posters, How do I convert a hexidecimal string, traditionally used for defining colors with HTML, into a floating point array? In other words, how do I convert...
1
by: Meya-awe | last post by:
Hello there, I am using a 3rd party library and a function which requires a float value in one of its methods. My data is in a string format and i tried using Convert.ToDouble and...
3
by: dean.elwood | last post by:
Hi guys, My first post here and I'm a pascal coder doing his best to move to C/C++ so please go easy on me ;) I'm using the MySQL C API to pull some values from a DB. One of the fields is a...
8
by: SpreadTooThin | last post by:
Basically I think the problem is in converting from a 32 bit integer to a 16 bit integer. I have two arrays: import array a = array.array('L', ) b = array.array('H', ) b = a
3
by: pipe.jack | last post by:
I'm trying to convert string to float and my float after conversion is 0 (zero). Here is my code: $c = $currencies->format($cart->show_total()); echo gettype($c); echo (float)$c; $c = 39.59...
3
by: psbasha | last post by:
Hi , When ever we read any data from file ,we read as a single line string ,and we convert the respective field data available in that string based on the data type ( say int,float ). ...
7
by: DirtyRasa | last post by:
Here is what my professor told me to to. Write a function that converts a string to a float and returns a float. Test your function by entering f4 and with 4f. Both should say Data entered was...
7
by: ma740988 | last post by:
Consider the equation (flight dynamics stuff): Yaw (Degrees) = Azimuth Angle(Radians) * 180 (Degrees) / 3.1415926535897932384626433832795 (Radians) There's a valid reason to use single...
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.