Data will be lost when double is converted to float.

Source: Internet
Author: User



For example, the following statement:


Float floatval = 3.15884534;


This 3.15884534 will be changed to 3.15885 and saved in floatval. That isFloat is precise to the fourth digit after the decimal point.




When reading from a file, read by double first


For example, my tmp.txt contains a 2.446789 number (note that there are six digits after a small number of points)


Run the followingCode:


Const char * test_file_name = "C: // tmp.txt"; <br/> void testreadfloatfromfile () <br/>{< br/> float floatval = 0; <br/> ifstream ifstr (test_file_name); <br/> ifstr> floatval; <br/> cout <"floatval =" <floatval <Endl; <br/> ifstr. close (); <br/> system ("pause"); <br/>} 


The running result is:


Floatval= 2.44679


2.446789 is changed to 2.44679, which means that the last digit (the fifth digit) is the rounding estimate.


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: 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.