C++ solution to the data accuracy problem of stores specified decimal places on floating point Numbers

  • 2020-05-27 06:36:57
  • OfStack

1, the background

Saves the specified decimal number for the floating point number. For example, 1.123456. To save 1 decimal place, after calling the method, the saved result is: 1.1. For another example, 1.98765, the result of saving 2 decimal places is: 2.00.

2. Solutions

A, add header file


#include <sstream> 
#include <iomanip> 

B, add a namespace


using namespace std; 

C, add function


    /************************************************************************/ 
/*  The function name: round 
/*  Function function: data precision calculation function  
/*  Function parameters: float src : precision number to be found    int bits Precision: ( 0 To keep after the decimal point 0 Decimal places. 1 Said to keep 1 Decimal places. 2 : represents a reservation 2 Decimal places)  
/*  Function return value: precision results  
/* Author: Lee 
/************************************************************************/ 
float round(float src, int bits); 

function


float CDemo1Dlg::round(float src, int bits) 
{ 
  stringstream ss; 
  ss << fixed << setprecision(bits) << f; 
  ss >> f; 
   return f; 
 
} 

D, call mode


CString str2 = L"99.054"; 
float f2 = (float)_wtof(str2); 
f2 *= 10; 
f2 = this->round(f2, 2); 

E, pay attention to

For example, 1.05, double is expressed in the computer as 1.0499999997, and float as 1.0500000003, but they are actually the same as 1.05.
There are exceptions to the round square approach where the number of bits processed is 5, for example: 1.05, and the result of processing may be 1.0499999997. This is float, so you can do something else. Just test it a few more times

conclusion


Related articles: