控制double,float类型数据的精度

本文介绍了一个自定义函数,用于将double类型的数值精确到小数点后指定位数并进行四舍五入处理。通过示例展示了如何确保数值如8.494被正确处理为8.49,而8.495则处理为8.50。

 我们知道,计算机中double, float类型的数据常常需要你去确定到底四舍五入到小数点后的几位. 所以, 我专门写了一个函数来完成这个功能.

注意,下面我以保留小数点后两位来说明.如果想保留三位,四位......可以依此类推

//
//Here I analyze if the double data should be carry.
//For example, 8.494 should convert to 8.49. 8.495 should be 8.50.
//
double   RoundData(double d)  
{    
 double   dt = d * 100;
 double dCeilResult = ceil(dt);
 double   df   =   dCeilResult   -   dt   -   0.5f;
 if(df > 0.05) 
  return   floor(dt)/100.0; //Get the max int data that is less than variable "dt".
 else   if   (df < -0.05)  
  return  dCeilResult/100.0; //Get the minor int data that more than variable "dt". 
 else   if   (d > 0)                        
  return  dCeilResult/100.0; //If it is positive number, get the minor int data that  more than variable "dt".
 else
  return  floor(dt)/100.0; //If it is negative number, get the max int data that is less than variable "dt".  
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值