有没有办法将数字转换为读者友好格式? (例如$ 1.1k) [英] Is there a way to round numbers into a reader friendly format? (e.g. $1.1k)

查看:157
本文介绍了有没有办法将数字转换为读者友好格式? (例如$ 1.1k)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像Stackoverlow声望四舍五入,我希望用货币做同样的事情

Much like the Stackoverlow reputation rounding, I'm hoping to do the same thing with currency

$ 1,000 => 1k

$1,000 => 1k

$ 1,000,000 => 1m

$1,000,000 => 1m

我如何在JavaScript中实现这一点(最好是在jQuery中)?

How can I achieve this in JavaScript (preferably in jQuery)?

推荐答案

这是一个简单的函数:

function abbrNum(number, decPlaces) {
    // 2 decimal places => 100, 3 => 1000, etc
    decPlaces = Math.pow(10,decPlaces);

    // Enumerate number abbreviations
    var abbrev = [ "k", "m", "b", "t" ];

    // Go through the array backwards, so we do the largest first
    for (var i=abbrev.length-1; i>=0; i--) {

        // Convert array index to "1000", "1000000", etc
        var size = Math.pow(10,(i+1)*3);

        // If the number is bigger or equal do the abbreviation
        if(size <= number) {
             // Here, we multiply by decPlaces, round, and then divide by decPlaces.
             // This gives us nice rounding to a particular decimal place.
             number = Math.round(number*decPlaces/size)/decPlaces;

             // Handle special case where we round up to the next abbreviation
             if((number == 1000) && (i < abbrev.length - 1)) {
                 number = 1;
                 i++;
             }

             // Add the letter for the abbreviation
             number += abbrev[i];

             // We are done... stop
             break;
        }
    }

    return number;
}

输出:

abbrNum(12 , 1)          => 12
abbrNum(0 , 2)           => 0
abbrNum(1234 , 0)        => 1k
abbrNum(34567 , 2)       => 34.57k
abbrNum(918395 , 1)      => 918.4k
abbrNum(2134124 , 2)     => 2.13m
abbrNum(47475782130 , 2) => 47.48b

演示: http://jsfiddle.net/jtbowden/SbqKL/

这篇关于有没有办法将数字转换为读者友好格式? (例如$ 1.1k)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆