简体   繁体   中英

Ho can I convert a number with 4 decimals in 2 decimals (HTML AND JS)

<!DOCTYPE html>
<html>
    <body>
        <meta name="viewport" conent="width=device-width, initial-scale=1">
        <title>Cryptocurrency Magex</title>
        <h3>JavaScript Math.round()</h3>
        <p>format a number with two decimals</h3>
        <p id="result">Number after formatting:<br></p>
        <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
        <script>
            var final = Math.round(btc*100)/100;
            document.getElementById("result").innerHTML += final;
      
            var btc = document.getElementById("bitcoin_price")
      
            var api = {
               "assync":true,
               "scrossDomain": true,
               "url":"https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_market_cap=true&include_24hr_vol=true&include_24hr_change=true&precision=2",
               "method":"GET",
               "headers":{}}
          
          $.ajax(api).done(function (response){btc.innerHTML = response.bitcoin.usd;});
      
         </script>
    </body> 
</html>

It returns me "NaN". How can I convert it to 2 decimals? Or I can´t convert numbers from api in js? If I try to put some fixed value, it works. But with api it doesn´t.

Change:

var api = { "assync":true, …

To „async“: true

I think you ll get the right decimal number. Otherwise use.toFixed(2) but it converts it to a string which you can convert to a number with +.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM