簡體   English   中英

Javascript格式編號API

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM