C + + to solve the problem of data accuracy, floating point to save the location of decimal __c++

Source: Internet
Author: User
Tags reserved

1. Background

To save a floating point number is to position a decimal.   For example, 1.123456. To save a 1-bit decimal, the method is invoked and the result saved is: 1.1. For example, 1.98765, the result of saving 2 decimal places is: 2.00.


2. Solution

A, add header file

#include <sstream>
#include <iomanip>
B, add namespaces

using namespace Std;

C, add a function

        /************************************************************************/
	/* Function name: round
	/* Function function: Data precision calculation function
	/* function parameter: float src: Refinement degree     int bits: precision (0 for 0 decimal places after the decimal point, 1 for reserved 1 decimal digits, 2 for reserved 2 decimal places)//
	function return value: Precision result/
	* Author:  Lee
	/************************************************************************/
	float round (float SRC, int bits);
function implementation

float Cdemo1dlg::round (float src, int bits)
{
	StringStream ss;
	SS << Fixed << setprecision (bits) << F;
	SS >> F;

	return f;

}


D, how to call

	CString str2 = L "99.054";
	float F2 = (float) _wtof (str2);
	F2 *=;
	F2 = This->round (F2, 2);

E, attention

For example, 1.05, double is represented in the computer as 1.0499999997, and float is represented as 1.0500000003, but it is actually equal to 1.05.

The round-side approach has an exception to the number of digits processed, such as: 1.05, which may result in 1.0499999997. Here is the float, you can switch to other types. I'll see how many times I have to test it.

/////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////

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.