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;
}
分享到:
相关推荐
4. **舍入和截断**:根据精度需求,对乘积进行适当的舍入或截断。这可能涉及到比较尾数的某一位是否大于或等于5,并相应地调整下一位。 5. **异常处理**:考虑可能出现的特殊情况,如零乘、无穷乘、非数字乘以及...
* 编程实现从键盘输入任意一个 float 型数据,然后将该数保留两位小数输出 * 编程实现从键盘上输入任意一个小写字母,然后将该字符转换为对应大写字母输出,并同时输出该字母的 ASCII 码值 八、编程题 * 编程实现...
但Turbo C 规定小数后最多保留六位,其余部分四舍五入。 [Practice] //floatint a=32; float b; double d; b=12345678; d=b*100; d=d+a; d=d+58.123456;'Vtable a,2,32 b,4,0.0 d,8,0.0 of Vtable 'Vupdate 1,32 2,0...
`CString`是MFC提供的字符串类,可以方便地进行字符串操作。与`char[]`之间的转换通常通过`CString::GetBuffer`和`CString::SetString`函数来实现。 #### 39. 关闭程序 关闭程序可以通过调用`PostQuitMessage`函数...