我在谷歌电子表格中使用JavaScript。我想将一个数字转换成游戏中的“货币”表示,即"X黄金X银X铜“。100铜是1银,100银是1金。
我在网上找到了这个功能:
/**
* Formats the sell value as "Ng Ns Nc" to match the ingame display string.
*/
function formatAsGold(sellValue) {
var n = sellValue;
var s = "";
if (sellValue < 0) {
s = "-";
n = Math.abs(n);
}
var gold = Math.floor(((n / 10000) % 100));
var silver = Math.floor(((n / 100) % 100));
var copper = Math.floor((n % 100)) + "c";
if (gold == 0) {
gold = "";
} else {
gold += "g ";
}
if (silver == 0) {
silver = "";
} else {
silver += "s ";
}
return s + gold + silver + copper;
}问题是,它不能正常工作:
a number: 2293900
produces the string: 29g 39s 0c
should be: 229g 39s 0c我该怎么解决这个问题?
发布于 2015-12-05 16:27:53
假设2293900是铜币的数量,并且你想要计算出你需要多少金牌、银牌和铜牌才能满足这个要求,这可能会有所帮助.
mod操作符返回除以mod数(在本例中为100 )后提供的数字的其余部分。所以,这是必要的银和铜,但不是黄金。首先确定金块,然后使用% 100来确定银,然后铜不包括更大的价值的金币。
var gold = Math.floor(n / 10000);
var silver = Math.floor(((n / 100) % 100));
var copper = Math.floor((n % 100)) + "c";在确定“战利品”的黄金部分时,没有更高的价值可以排除,所以在计算黄金部分时失去% 100。
JSFiddle例子。
https://stackoverflow.com/questions/34107473
复制相似问题