Question

atof inaccuracy

Asked by: marcodalzotto

Hi experts, I'm trying to convert a string to a double.

double d = atof("245.76");

The d variable become 245.75999999999999.

I need to have a double 245.76000000000000.

How suggest to fixit?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-01-24 at 02:41:53ID22134470
Tags

atof

Topic

C++ Programming Language

Participating Experts
5
Points
500
Comments
15

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Linux atof problem
    I have a C++ program that reads in a binary string, parses it into character arrays and converts some of them to doubles with atof. It works fine on the Sun Sparcs on which the data is stored. However, when I compile and run the program on Linux, the program bombs. After d...
  2. Puzzling atof...urgent!!! :(
    hi guys, I have a puzzling atof conversion here.. on Unix I have a custom round up function : char * round_up(value, noofdecimal) char *value; /* val to round up*/ int noofdecimal; /* no of decimals */ { ...... code...... return (&rtnval); } an...
  3. atof function returns 0/-1.#INF0000000
    Using the atof() function, I try convert both a CString and a char to a double. When I try to convert a number with 00 after the decimal point, ie "10"/"10.00" the function sometimes returns either 0 or -1.#INF00000, and sometimes the real values, ie 10. ...
  4. Problem with using atof() function
    Hi Experts Urgent! I'm coding this for my company project-- I'm having some problems with this code: #include <dos.h> #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <graphics.h> #include <time.h> #include <string.h&g...
  5. atof and CString
    in MFC I can do this: CString s1("1.99") double num = atof((char *)(const char *) s1); in winCE I get this error: error C2664: 'atof' : cannot convert parameter 1 from 'class CString' to 'const char *' Unicode is the issue. How do I convert CString to a double?
  6. atof problem !
    hi all, I have a big problem using the atof function. I have an MDI application using MFC Test code : CString str = "2.32"; double fVal = atof(str); CString x; x.Format("%f - %s", fVal, str); AfxMessageBox(x); (RELEASE) If I call the test code in ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Infinity08Posted on 2007-01-24 at 03:11:18ID: 18384540

What's the output of this program :

    #include <iostream>
   
    int main(void) {
      double d = atof("245.76");
      std::cout << d << std::endl;
      return 0;
    }

I get the correct result.

In any case, if you want exact precision, then a double is probably not what you want (it's a floating point number).

What do you need this for ? For certain applications, fixed point could be an option ...

 

by: marcodalzottoPosted on 2007-01-24 at 03:39:17ID: 18384655

I get the correct results.

I get the correct results even if I use the sprintf with "%f". because sprintf approximate.

The "245.76" string came from a MySQL database. And I need it as a double because I make some calculation.

I have tried to approximate the double value with the function form http://www.experts-exchange.com/Programming/Programming_Languages/C/Q_20412254.html?query=fprec&clearTAFilter=true

double fprec(double f,int prec)
{
 double p = pow(10,prec);
 return floor(f*p)/p;
}

But it returns the same thing.

 

by: marcodalzottoPosted on 2007-01-24 at 03:49:23ID: 18384698

It incredible! Even changing the variable with the debugger from "245.75999999999999" to "245.76000000000000" and if I put with the debugger "245.76000000000001" i get "245.76000000000002".

From that I can understand that is a resolution problem... but how can I sove it? How ca I fix the resolution for a double?

 

by: marcodalzottoPosted on 2007-01-24 at 03:53:41ID: 18384720

Sorry, my thought run fater than my keyboard :)

It incredible! Even changing the variable with the debugger from "245.75999999999999" to "245.76000000000000" I get again "245.75999999999999".
And if I put with the debugger "245.76000000000001" I get "245.76000000000002".

From that I can understand that is a resolution problem... but how can I sove it? How can I fix the resolution for a double?

 

by: grg99Posted on 2007-01-24 at 03:56:06ID: 18384732

The problem is in a sense, unsolvable.

Numbers in the computer are usually stored in binary format.  For a floating-point number, it's a binary fraction with a binary power of two scale factor.  It's unlikely a decimal number will be exactly representable.

But you can round it-- use a print format with two decimal places and the print function will round the number to two decimal places.

 

by: marcodalzottoPosted on 2007-01-24 at 04:16:39ID: 18384879

>> But you can round it-- use a print format with two decimal places and the print function will round the number to two decimal places.

The round that makes printf is the issue. I try to explay what is appening in my project.

I have a variable soglia = -43.519999999999996 (it cames from a calculation)
I update to a MySQL database this variable through sprintf using %f
The sprintf transforms the soglia variable into -43.52
When I get back tha soglia value from the databse I have to transorm the "-43.52" in to a double.
Using the atof function like atof("-43.52") I get a double sogliadb = -43.520000000000003

So, If I want to compare the variable soglia = -43.519999999999996 with the variable I get form the database sogliadb = -43.520000000000003 I get difference.

How would you suggest to solve it?

 

by: itsmeandnobodyelsePosted on 2007-01-24 at 04:17:18ID: 18384885

>>>> The problem is in a sense, unsolvable.

Don't think so. The problem is the convertion to a double. If you would read the variable to a string and only convert for calculations you won't get the problem. Another 'solution' is to store the count of the fractional digits (of course you don't need to store it if you *know* that it is always 2) and make an appropriate rounding when outputting the number. Again, the problem is an output problem only. 245.75999999999999 is as good as 245.76 if used for calculations. For output you can do that:

#include <iomanip>
#include <iostream>
using namespace std;

     double d = atof("245.76");

     cout << fixed << setprecision(2) << d << endl;

You also could set the precision generally for cout by

     cout.precision(2);

If fixed or scientific is set, setprecision determines the number of fractional digits (digits right of the period). If not it determines the number of significant digits (5).

Regards, Alex

 

by: Infinity08Posted on 2007-01-24 at 04:20:29ID: 18384903

>> I get the correct results.
Then I don't really understand your problem. Can you post your code that converts the string "245.76" to a double and when showing the double, it gives "245.75999999999999" ?

Anyway, like grg said : a double has only about 15 digits of precision (which is enough for most applications). If you need more precision, then you'll need to use a custom datatype instead.

As I asked earlier : what do you use this for ?

 

by: Infinity08Posted on 2007-01-24 at 04:26:25ID: 18384953

>> So, If I want to compare the variable soglia = -43.519999999999996 with the variable I get form the database sogliadb = -43.520000000000003 I get difference.

You can always compare them like this :

    double precision = 0.00000000001;
    if (fabs(sogliadb - soglia) < precision) {
      // equal
    }
    else {
      // different
    }

Make sure that the precision you choose remains within the double precision (about 15 digits)

 

by: 0xC0DEB07Posted on 2007-01-24 at 04:59:11ID: 18385159

As stated above the floating point numbers are just a mathematical approximation.
Anyway the problem here seems to be in the output function.

Alex ( itsmeandnobodyelse ) proposed something like:

      cout << fixed << setprecision(2) << d << endl;

This is OK if the input string represents exactly 2 digits after the floating point, but if there are more, the output will be rounded.
A more general way to display the correct value of a floating point number in C++ would be:

        double d = atof("245.769");
        std::cout.setf(std::ios::floatfield);
        std::cout << d << std::endl;

This way the output is not rounded at all.

 

by: AlexNekPosted on 2007-01-24 at 05:01:25ID: 18385176

If you have a limited range of variable value you can use an old trick for 2 decimal number after point.
Round variable, multiplay variable by 100 and store as integer.

 

by: itsmeandnobodyelsePosted on 2007-01-24 at 06:03:31ID: 18385608

>>>> std::cout.setf(std::ios::floatfield);
>>>> std::cout << d << std::endl;

with that d was rounded to 6 significant digits (default).  

>>>> this way the output is not rounded at all.

That isn't true. Take      

   double d = atof("1245.769");

and you will see that the output is 1245.77.

   double d = atof("0.76999999");

gives  0.769999 as output.

Or worse:

       double d = atof("245.76124599999999");
       std::cout.setf(std::ios::floatfield);
       std::cout << d << std::endl;

would round to 245.76 !!!

So, with format flags you only can decide whether you want rounding dependent on the number of fractional digits or dependent on significant digits. If you only want to round differences that came from conversion decimal to binary and vice versa, you need to set the precision to 14 (significant digits) and set the format to floatfield.

       double d = atof("245.76124599999999");
       std::cout.setf(std::ios::floatfield);
       std::cout.precision(14);
       std::cout << d << std::endl;

So, only the combination of floatfield and precision(14) will give a correct result..

Regards, Alex

 

by: marcodalzottoPosted on 2007-01-24 at 06:08:21ID: 18385641

I think the easier way to do it is to follow the suggestion of AlexNek.
Another good way would be to compare setting the pecision as Infinity08 wrote.

Thanks for your suggestions.

 

by: itsmeandnobodyelsePosted on 2007-01-24 at 06:55:08ID: 18386093

>>>> I think the easier way to do it is to follow the suggestion of AlexNek.

You may have overread that he suggests, *Round* variable, multiply variable by 100 and store as integer.

You can do rounding by adding 0.5 before multiplying. Then 123.455 would turn to 123.460 and the integer*100 is 12346, correctly rounded. 123.544 would give 123.549 and finally 12354, what is correct as well. So 0, 1, 2, 3, 4 for the digit to round would be rounded down while 5, 6, 7, 8, 9 would round up. Following that the algorithm is

      int r100 = (int)((d +0.005)*100);

For output you need

   cout << r100/100 << '.' << r100%100;

It isn't easier or more transparent than  

   cout << fixed << precision(2) << d;  

Regards, Alex


 

by: itsmeandnobodyelsePosted on 2007-01-24 at 06:57:20ID: 18386118

>>>> by adding 0.5 before multiplying

It should mean 'by adding 0.5 after multiplying' or 'by adding 0.005 before multiplying'

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...