vc将字符串表示的任意位数字进行小数位保留和四舍五入
BOOL SHGlobal::isIntOrDecimal(CString strItem)
{
// 判断是否为整数或小数
// 返回 0 代表不是
// 返回 1 代表整数
// 返回 2 代表小数
if(strItem.IsEmpty())
return FALSE;
for(int i = 0; i <strItem.GetLength(); i++)
{
// check "+ "、 "- "
if(i == 0 && (strItem.GetAt(i) == 0x2B || strItem.GetAt(i) == 0x2D))
continue;
// check char
if( !isdigit(strItem.GetAt(i)) && strItem.GetAt(i) != '.')
return FALSE;
}
// check 小数点
if(strItem.Find( '.') != strItem.ReverseFind( '.'))
return FALSE;
return TRUE;
}
// tS 表示被操作的字符串
// tDecimalCount 表示需要保留的小数位数
// tRound 表示是否进行四舍五入操作
// addLenWhenLarger 表示四舍五入后超过当前长度的范围了是否增加位数
CString SHGlobal::strRound(CString tS, int tDecimalCount, boolean tRound, boolean addLenWhenLarger)
{
if(!isIntOrDecimal(tS))
AfxMessageBox(_T("非法数字不能进行格式化"));
int strLen = tS.GetLength();
int dotIndex = tS.Find('.'); // 小数点的位置
int i = 0 ;
if(dotIndex < 0 && tDecimalCount <= 0)// 本身是整数并且不需要小数位
{}
else if(dotIndex < 0 && tDecimalCount > 0) // 本身是整数,但需要增加小数位
{
tS += ".";
for(i =0 ; i < tDecimalCount; i++)
tS += "0";
}else if(dotIndex > 0 && dotIndex + tDecimalCount + 1 >= strLen)
// 本身有小数位但小数位数小于或等于需要保留的小数位
{
int tDots = (dotIndex + tDecimalCount + 1) - strLen;
for(i =0 ; i < tDots; i++)
tS += "0";
}else if(dotIndex > 0 && dotIndex + tDecimalCount + 1 < strLen){
// 本身有小数位并且小数位数大于需要保留的小数位,需要进行格式化
if(!tRound){
// 不需要四舍五入
tS = tS.Mid(0, dotIndex + tDecimalCount + 1);
}
else{
// 需要四舍五入
if(tS.GetAt(dotIndex + tDecimalCount + 1) < '5'){
// 保留小数位的后一位小于五
tS = tS.Mid(0, dotIndex + tDecimalCount + 1);
}else{
// 从最后位向前进行进位判断
tS = tS.Mid(0, dotIndex + tDecimalCount + 1);
boolean needtoAdd = TRUE; // 是否有进位
for(i = tS.GetLength() - 1; i >=0 ; i--){
if(needtoAdd){
char tCC = tS.GetAt(i);
if(tCC == '.')
continue;
tCC++;
if(tCC > '9'){
// 产生进位
tCC = '0';
tS.SetAt(i,tCC);
needtoAdd = TRUE;
}else {
needtoAdd = FALSE;
tS.SetAt(i,tCC);
break;
}
}
}
if(needtoAdd && addLenWhenLarger){
// 当第一位也需要进位时并且允许进位时
tS = "1" + tS;
}
}
}
}
return tS;
}