当前位置:编程学习 > 网站相关 >>

截取浮点数小数点后指定位数的一种做法

作者:朱金灿
来源:http://blog.csdn.net/clever101/

 


      对浮点数进行小数点后指定位数输出经常是日常编程中遇到的一个问题。令我稍感奇怪的是网上这方面的资料不多。实际上这种指定有效位数输出有时要经历四舍五入的变换。晚上参考了网上一篇文章的做法,实现了一个函数:

 


   /*!
*  @brief 对浮点数四舍五入后指定位数输出
*
*  @param dbNum  [in]待处理的浮点数
*  @param decplaces [in]小数点后的位数
*  @return 输出字符串
*/
std::string NumRounding(double dbNum,int decplaces)
{
 // stringstream对象默认精度为,这里利用numeric_limits将精度设置为long double覆盖默认精度
 int prec=std::numeric_limits<long double>::digits10;
 std::ostringstream oss;
 oss.precision(prec);
 oss<<dbNum;
 std::string strNum = oss.str();
 // 求取小数点位置
 size_t DecPos = strNum.find(.);
 // 若找不到小数点,就直接返回
 if(DecPos==std::string::npos)
  return strNum;
 //假如原有的小数点位数小于等于有效位数
 size_t len = strNum.size();
 if((len-DecPos-1)<=decplaces)
  return strNum;
 // 先进行四舍五入,比如输出四舍五入一位,就加.05
 int nTmp = decplaces+1;
 double exa = 1.0;
 while(nTmp--)
 {
  exa = exa/10.0;
 }
 double dbAppen = 5*exa;
 double tmp = dbNum + dbAppen;
   
    // 清空缓存,重新进行格式化
 oss.str("");
 oss<<tmp;
 std::string strResult = oss.str();
 // 截取字符串
    strResult = strResult.substr(0,strResult.find(.)+decplaces+1);
 return strResult;

 


   测试代码:

 


   int _tmain(int argc, _TCHAR* argv[])
{
 double dbNum = 10.1234;
 int decplaces=2;
 std::string str = NumRounding(dbNum,decplaces);
 float dbResult = atof(str.c_str());
 double dbResult2 = atof(str.c_str());
 return 0;


思考题:

 


1.测试代码中dbResult和dbResult2有什么区别吗?为什么有这种区别呢?(提示:float和double的精度不同)。

 

 

 

参考文献:

 


1. 小数点后截位问题 ,作者:牛司朋。


 

补充:综合编程 , 其他综合 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,