金额元格式化

mfc版本的非标准元金额转换成标准元格式金额

CString formatYuan(const char* yuanAmount)
{
    CString fmtAmt = yuanAmount;
    fmtAmt.TrimRight();
    fmtAmt.TrimLeft();
  int strLen = fmtAmt.GetLength();
    if( strLen == 0 || fmtAmt == "-" || fmtAmt == "." || fmtAmt == "-." ){return "0.00";
    }

    bool isInvalid = false;
    TCHAR ch;
    short dotCount = 0;
    short ltZeroCount = 0;
    for(int i=0; i<strLen; i++)
    {
        ch = fmtAmt.GetAt(i);
        if( ch == '-' ){
            if( ++ltZeroCount > 1 ){
                isInvalid = true;break;
            }else{
                continue;
            }
        }
        if( ch == '.'  ){
            if( ++dotCount > 1 ){
                isInvalid = true;
                break;
            }else{
                continue;;
            }
        }
        if( ch >= '0' && ch <= '9' ){
            
        }
        else{            
            isInvalid = true;
            break;
        }
    }
    if(isInvalid || (ltZeroCount == 1 && fmtAmt.GetAt(0) != '-') ){return fmtAmt;
    }

    ch = 0;
    if( fmtAmt.GetAt(0) == '-' ){
        ch = '-';
        fmtAmt = fmtAmt.Right(fmtAmt.GetLength()-1);
    }
        
    int dotIdx = fmtAmt.Find('.');
    if( dotIdx == -1 ){// cant't find dot
        if( fmtAmt.GetLength() > 1 ){
            fmtAmt.TrimLeft('0');
            if( fmtAmt.GetLength() == 0 ) fmtAmt = "0";
        }
        if( ch != 0 ){
            fmtAmt.Insert(0,ch);
        }
        fmtAmt += ".00";
    }
    else{
        CString dotBefore = fmtAmt.Left(dotIdx);
        CString dotAfter = fmtAmt.Right(fmtAmt.GetLength()-dotIdx-1);switch(dotBefore.GetLength())
        {
        case 0:
            dotBefore = "0";
            break;
        case 1:
            break;
        default:
            dotBefore.TrimLeft('0');
            if( dotBefore.GetLength() == 0 ) dotBefore = "0";break;
        }

        switch(dotAfter.GetLength())
        {
        case 0:
            dotAfter = "00";
            break;
        case 1:
            dotAfter += "0";
            break;
        default:
            dotAfter = dotAfter.Left(2);
            break;
        }

        fmtAmt = dotBefore + '.' + dotAfter;
        if(ch!=0){
            fmtAmt.Insert(0,ch);
        }
    }
if( fmtAmt == "-0.00" ){
        fmtAmt = "0.00";
    }return fmtAmt;
}

 

posted @ 2021-12-17 13:41  晨光静默  阅读(73)  评论(0编辑  收藏  举报