我这里有很多问题。我在javascript中使用nFormatter用于大数字,但我不知道如何在现有代码中使用它。
这是我正在使用的格式化程序。
function nFormatter(num) {
if (num >= 1000000000000) {
return (num / 1000000000000).toFixed(1).replace(/\.0$/, '') + 'Trillion';
}
if (num >= 1000000000) {
return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'Billion';
}
if (num >= 1000000) {
return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'Million';
}
if (num >= 1000) {
return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'Thousand';
}
return num;
}
nFormatter;
我需要将此代码添加到我的其他代码中,但我不确定我将如何执行此操作。
这是我目前的代码。
var gameProfit = 5000;
var tinyOwned = 0;
var tinyCost = 5000;
var tinyIncome = 0;
function tinyGamePlay() {
if (gameProfit >= tinyCost) {
tinyOwned++;
gameProfit -= tinyCost;
tinyIncome = 15000 * tinyOwned;
tinyCost = 5000 * tinyOwned;
document.getElementById('tiny-owned').innerHTML = tinyOwned;
document.getElementById('tiny-income').innerHTML = "Income : $ " + tinyIncome;
document.getElementById('tiny-cost').innerHTML = "Next Cost : $ " + tinyCost;
document.getElementById('currentProfit').innerHTML = "Profit : $ " + gameProfit;
}
}
tinyGamePlay;
所以我的所有变量一次都会超过1000,所以格式化程序需要在我的所有变量上使用。
我不介意使用JS插件,如果有人知道可以帮助的东西,
有人可以帮忙吗?
答案 0 :(得分:1)
您只需要在打印输出时调用此nFormatter
函数,请参见下面的剪辑,您可以使用更大的数字http://jsfromhell.com/classes/bignumber:
function nFormatter(num) {
if (num >= 1000000000000) {
return (num / 1000000000000).toFixed(1).replace(/\.0$/, '') + ' Trillion';
}
if (num >= 1000000000) {
return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + ' Billion';
}
if (num >= 1000000) {
return (num / 1000000).toFixed(1).replace(/\.0$/, '') + ' Million';
}
if (num >= 1000) {
return (num / 1000).toFixed(1).replace(/\.0$/, '') + ' Thousand';
}
return num;
}
var gameProfit = 5100;
var tinyOwned = 0;
var tinyCost = 5000;
var tinyIncome = 0;
function tinyGamePlay() {
if (gameProfit >= tinyCost) {
tinyOwned++;
gameProfit -= tinyCost;
tinyIncome = 15000 * tinyOwned;
tinyCost = 5000 * tinyOwned;
console.log(tinyCost);
document.getElementById('tiny-owned').innerHTML = nFormatter(tinyOwned);
document.getElementById('tiny-income').innerHTML = "Income : $ " + nFormatter(tinyIncome);
document.getElementById('tiny-cost').innerHTML = "Next Cost : $ " + nFormatter(tinyCost);
document.getElementById('currentProfit').innerHTML = "Profit : $ " + nFormatter(gameProfit);
}
}
tinyGamePlay();
<p id="tiny-owned"></p>
<p id="tiny-income"></p>
<p id="tiny-cost"></p>
<p id="currentProfit"></p>