由于需要,将float/double 四舍五入后保留四位小数(可以根据需要修改不同的小数保留位数),主要充分利用各种数据之间的转化关系。
C++代码:
#include <iostream>
#include <cstdlib>
using namespace std;
float float4(double a)
{
float need;
if (a * 10000 - int(a * 10000) >= 0.444444444445)
need = (float)(int(a * 100000) / 10 + 1) / 10000;
else
need = (float)(int(a * 100000) / 10) / 10000;
return need;
}
int main()
{
double a = 1.2345444445;
double b = 1.234444444444;
a = float4(a);
b = float4(b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
system("pause");
return 0;
}
验证结果: