How to avoid loss of precision when converting a string to a floating point number?

Source: Internet
Author: User

The function for converting a string to a floating point number. The function provided by standard C is atof (char *). c ++ Builder provides a function strtofloat (ansistring *), however, if you directly define a floating-point variable and convert the string to a single-precision floating-point variable, there may be problems with precision errors. The following is a simple example.

Char * strdemo = "0.00100 ";

Float fdat;

Fdat = atof (strdemo );

Showmessage (fdat );

AboveCodeThe computation result is: 0.00100000004749475, with a significant Conversion error.

The function definition for converting a string to a floating point: Double atof (const char * s );

The Return Value Type of the atof () function is double. If you assign a value to a single-precision floating point number, there must be a loss of precision. The cause is found, modify the float in the above Code to double and compile and run the program. The result is 0.001.

OK! Solve the problem.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.