JavaScript - 可读格式的秒数?

时间:2014-05-05 21:24:42

标签: javascript

我有一个带有1,235,752,564,445,799,865,346等数字的变量 - 如何将其转换为可读的格式,而不是大号,将其显示为4 quadrillion centuries,或者实际的等价物?

因此,例如29030400000秒将显示为1 millennium

1 个答案:

答案 0 :(得分:0)

我会使用两个缩放功能。这是some demo code适用于"尺蛾"通过不同缩放因子的数组。 YMMV。

var p = function (n) { return Math.pow(10, n) }

// Searching a sorted of array of "scaling factors" to find the
// first scale such that x/scale >= 1 and x/scale < limit, handling
// cases where these conditions cannot be met.
//
// Returns { scaled: number, name: scalingName }
function scaleInto(x, limit, es) {
    var beste = es[0];   
    for (var i = 1; i < es.length; i++) {
        var e = es[i];
        var scaled = x / e.scale;
        // Scaling fits, or last scale
        if (scaled >= 1
            || i == (es.length - 1)) {
            beste = e;
        }
        if (scaled < limit) {
            break;
        }
    }

    return {
        scaled: x / beste.scale,
        name: beste.name
    }
}

var timeScale = [
    {name: "year", scale: 1 },
    {name: "decade", scale: p(1) },
    {name: "century", scale: p(2) },
    {name: "millenium", scale: p(3) }
]

/* short-scale */
var modScale = [
    {name: "", scale: 1 },
    {name: "hundred", scale: p(2) },
    {name: "thousand", scale: p(3) },
    {name: "million", scale: p(6) },
    {name: "billion", scale: p(9) },
    {name: "trillion", scale: p(12) },
    {name: "quadrillion", scale: p(15) }
]

function humanizeYears(years, ts, ms) {
    if (years < 1) {
        return "less than a year"
    }
    var r1 = scaleInto(years, 100, ts || timeScale);
    var r2 = scaleInto(r1.scaled, 100, ms || modScale)
    if (r2.name) {
        return r2.scaled.toFixed(0) + " " + r2.name + " " + r1.name
    } else {
        return r2.scaled.toFixed(0) + " " + r1.name
    }
}

function humanizeSeconds(seconds, ts, ms) {
    var years = seconds / (3600 * 24 * 365.25)
    console.log("years: " + years)
    return humanizeYears(years, ts, ms);
}

使用和输出:

// -> 92 decade
console.log(humanizeSeconds(29030400000))             
// -> 39 billion millenium
console.log(humanizeSeconds(1.2357525644457998e+21))

var centuriesOnly = timeScale.filter(function (v) {
    return v.scale <= p(2);
});
// -> 392 billion century 
console.log(humanizeSeconds(1.2357525644457998e+21, centuriesOnly))