把大資料數字口語化(python+js)

pythontab發表於2013-02-23

當出現萬以上的整型數字時,經常要把它們口語化比較直觀。下面分享兩段程式碼,python與js的

python

def fn(num):
    '''
    把數字口語化
    '''
     
    ret = ''
    num = int(num)
    if num/10000 == 0:
        ret = str(num)
    else:
        if num/10**8 == 0:
            if num%10000 != 0:
                ret = str(num/10000) + '萬' + str(num % 10000)
            else:
                ret = str(num/10000) + '萬'
        else:
            n2 = num%10**8
            if n2%10000 != 0 and n2/10000 != 0:
                ret = str(num/10**8) + '億' + str(n2/10000) + '萬' + str(n2%10000)
            elif  n2%10000 != 0 and n2/10000 == 0:
                ret = str(num/10**8) + '億' +  str(n2%10000)
            elif  n2%10000 == 0 and n2/10000 != 0:
                ret = str(num/10**8) + '億' +  str(n2/10000) + '萬'
            elif  n2%10000 == 0 and n2/10000 == 0:
                ret = str(num/10**8) + '億'
    return ret


javascript:

function int2string(num) {
    num = Number(num);
    if (num/10000 < 1){
        ret = num;
    }else{
        if (num/Math.pow(10,8) < 1) {
            if (num%10000 != 0) {
                ret = parseInt(num/10000) + '萬' + num % 10000;
            }else{
                ret = parseInt(num/10000) + '萬';
            }
        }else{
            n2 = num%Math.pow(10,8);
            if (n2%10000 != 0 & n2/10000 != 0) {
                ret = parseInt(num/Math.pow(10,8)) + '億' + parseInt(n2/10000) + '萬' + (n2%10000);
            }else if(n2%10000 != 0 & n2/10000 == 0){
                ret = parseInt(num/Math.pow(10,8)) + '億' +  parseInt(n2%10000);
            }else if(n2%10000 == 0 & n2/10000 != 0){
                ret = parseInt(num/Math.pow(10,8)) + '億' +  parseInt(n2/10000) + '萬';
            }else if(n2%10000 == 0 & n2/10000 == 0){
                ret = (num/Math.pow(10,8)) + '億';
            }
        }
    }
    return ret
}



相關文章