c++、vc++ 数据精度、小数点取舍、数据四舍五入、保留2位小数、数据之间加入","

来源:互联网 发布:淘宝服装货源怎么找 编辑:程序博客网 时间:2024/05/22 00:05

 // 数据精度计算
 // 第一个参数为:代处理的数;
 // 第二参数个为:要保留小数点后几位
 CString DataPrecision(LPCTSTR lpszsrc, int nseveral);

 // 在数据中插入","分隔数据段
 CString DataInsertSeparator(LPCTSTR lpszsrc, int nseveral);

CString C***::DataPrecision(LPCTSTR lpszsrc, int nseveral)
{
 CString strreturn(lpszsrc);

  // 当值为""时
 if (0 == _tcsicmp(_T(""), strreturn)
  || 0 == _tcsicmp(_T("0"), strreturn)
  || 0 == _tcsicmp(_T("0.0"), strreturn)
  ||  0 == _tcsicmp(_T("0.00"), strreturn))                 
 {
  return _T("0.00");                                      // 默认给两位小数
 }

 int npos = strreturn.Find(_T("."));
 if (npos > 0)
 {
  CString strseveral = strreturn.Mid(npos + nseveral, 2);  // nseveral位小数所在的位和其后一位  
  int nmid = atoi(strseveral);                             // 取得两位数 
  
  // 计算是否需要进位
  if ((nmid%10) > 4 && (nmid%10) < 10)
  {
   nmid = nmid/10 + 1;  
   
  }else
  {
   nmid = nmid/10;
  }
  CString strmid(_T(""));
  strmid.Format(_T("%d"), nmid);
  strreturn.Delete(npos + nseveral, 1);                    // 从字符中删除保留位的数据  
  strreturn.Insert(npos + nseveral, strmid);               // 插入新的数据 
  
    strreturn = strreturn.Left(strreturn.Find(_T(".")) + nseveral +1);  // 取字符串小数点后nseveral位 
  
  strreturn = DataInsertSeparator(strreturn, nseveral); 

 }

 // "-1.#0" 错误值时
 if (strreturn.Find(_T("-")) >= 0 && strreturn.Find(_T("#0")) >= 0)
 {
  strreturn = _T("0.00");
 }

 return strreturn;
}

CString C***::DataInsertSeparator(LPCTSTR lpszsrc, int nseveral)
{
 CString strdata(lpszsrc);

 int npos = strdata.Find(_T("."));

 if (strdata.GetLength() > (4 + nseveral))     // 数据如:1,000.12
 {
  strdata.Insert(npos - 3, _T(","));
 }
 if (strdata.GetLength() > (8 + nseveral))          // 数据如:1,000,000.12
 {
  strdata.Insert(npos - 6, _T(","));
 }
 if (strdata.GetLength() > (12 + nseveral))         // 数据如:1,000,000,000.12
 {
  strdata.Insert(npos - 9, _T(","));
 }
 if (strdata.GetLength() > (16 + nseveral))         // 数据如:1,000,000,000.12
 {
  strdata.Insert(npos - 12, _T(","));
 }
 if (strdata.GetLength() > (20 + nseveral))         // 数据如:1,000,000,000,000.12
 {
  strdata.Insert(npos - 15, _T(","));
 }

 if (0 == strdata.Find(_T("-")))                    // 如果是个负数,则负号后面不能带"," 如:-,654,999.55
 {
  if (1 == strdata.Find(_T(",")))
  {
   strdata.Delete(1,1);                       // 删除在第二位的字符","
  }
 }

 return strdata;
}

 

原创粉丝点击