首頁 >後端開發 >Python教學 >把大數據數字口語化

把大數據數字口語化

高洛峰
高洛峰原創
2016-10-18 13:28:281109瀏覽

當出現萬以上的整數數字時,常常要把它們口語化比較直觀。以下分享兩段程式碼,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) + &#39;万&#39; + num % 10000;
            }else{
                ret = parseInt(num/10000) + &#39;万&#39;;
            }
        }else{
            n2 = num%Math.pow(10,8);
            if (n2%10000 != 0 & n2/10000 != 0) {
                ret = parseInt(num/Math.pow(10,8)) + &#39;亿&#39; + parseInt(n2/10000) + &#39;万&#39; + (n2%10000);
            }else if(n2%10000 != 0 & n2/10000 == 0){
                ret = parseInt(num/Math.pow(10,8)) + &#39;亿&#39; +  parseInt(n2%10000);
            }else if(n2%10000 == 0 & n2/10000 != 0){
                ret = parseInt(num/Math.pow(10,8)) + &#39;亿&#39; +  parseInt(n2/10000) + &#39;万&#39;;
            }else if(n2%10000 == 0 & n2/10000 == 0){
                ret = (num/Math.pow(10,8)) + &#39;亿&#39;;
            }
        }
    }
    return ret
}


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn