[英]JavaScript - seconds to readable format?
我有一個變量,其數字為1,235,752,564,445,799,865,346
如何將其轉換為可讀形式,例如代替大數字,將其顯示為4 quadrillion centuries
,或實際等值?
因此,例如29030400000
秒將顯示為1 millennium
?
我將使用兩個縮放功能。 這是一些演示代碼 ,它們通過不同比例因子的數組應用“蠕蟲”。 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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.