473,382 Members | 1,376 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 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 3201
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.