[英]Javascript formatting numbers API
我的(javascript)API出现问题。 当我使用coinmarketcap API( https://api.coinmarketcap.com/v1/ticker )时。 至于比特币的“ max_supply”,它的文本为“ 16865112.0”。 这是个问题。 我想自动将逗号放在16,865,112.0之类的数字中。
例如,如果数据ID是以太坊(没有最大供给),则我为∞。 这样可行。
原版的:
$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) { for (var i = 0; i < data.length - 1; i++) { if (data[i].id == "bitcoin") { $("#max_supply").html(data[i].max_supply == null ? '∞' : data[i].max_supply); } } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="max_supply"></div>
这使我的输出为“ 21000000.0”
这就是我到目前为止
$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) { for (var i = 0; i < data.length - 1; i++) { if (data[i].id == "bitcoin") { $("#max_supply").html(Number(data[i].max_supply).toLocaleString('en-US') == null ? '∞' : data[i].max_supply.toLocaleString('en-US')); } } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="max_supply"></div>
这没有给我输出。
有什么建议么?
首先,您应该在for循环中取消-1
,否则您将丢失最后一项。
三元数maxSupply = maxSupply == null ? '∞' : numberWithCommas(maxSupply)
maxSupply = maxSupply == null ? '∞' : numberWithCommas(maxSupply)
下面的maxSupply = maxSupply == null ? '∞' : numberWithCommas(maxSupply)
表示如果最大供应量为空(对于来自JSON的当前硬币),则将maxSupply设置为∞
否则将maxSupply var设置为numberWithCommas(maxSupply)
我从https://stackoverflow.com/a/2901298/1309377获得了numberWithCommas(...)
函数,以按照您的要求用逗号格式化数字。
我还切换到了.append()
而不是.html()
否则您将只是在重写自己。
$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) { for (var i = 0; i < data.length; i++) { var coin = data[i].id; var maxSupply = data[i].max_supply; maxSupply = maxSupply == null ? '∞' : numberWithCommas(maxSupply) $("#max_supply").append(coin + ": " + maxSupply + "<br/>"); } }); function numberWithCommas(x){ return x.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ","); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span>Max Supply</span> <div id="max_supply"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.