Convert long number into abbreviated string in JavaScript, with a special shortness requirement

前端 未结 16 2516
名媛妹妹
名媛妹妹 2020-11-30 22:33

In JavaScript, how would one write a function that converts a given [edit: positive integer] number (below 100 billion) into a 3-letter abbreviation -- where 0-9 an

16条回答
  •  悲&欢浪女
    2020-11-30 22:39

    Intl is the Javascript standard 'package' for implemented internationalized behaviours. Intl.NumberFormatter is specifically the localized number formatter. So this code actually respects your locally configured thousands and decimal separators.

    intlFormat(num) {
        return new Intl.NumberFormat().format(Math.round(num*10)/10);
    }
    
    abbreviateNumber(value) {
        let num = Math.floor(value);
        if(num >= 1000000000)
            return this.intlFormat(num/1000000000)+'B';
        if(num >= 1000000)
            return this.intlFormat(num/1000000)+'M';
        if(num >= 1000)
            return this.intlFormat(num/1000)+'k';
        return this.intlFormat(num);
    }
    

    abbreviateNumber(999999999999) // Gives 999B

    Related question: Abbreviate a localized number in JavaScript for thousands (1k) and millions (1m)

提交回复
热议问题