0

I have searched and tried several times but still can't get it. How do I prepend "$" and round the value to the nearest 100th of a decimal. Example: $100.00

<script>
  $.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {
    for (var i = 0; i < data.length - 1; i++) {
      if (data[i].id == "unit") {
        $("#unit").html(parseFloat(data[i].price_usd) * 500000);
      }
    }
  });
</script>
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Simon Phoenix
  • 31
  • 1
  • 3

1 Answers1

2

Use Number.prototype.toFixed() to make fixed number of decimals, concatinate strings as usual, because toFixed returns string:

function toCurrency(value = 0, symbol = '$', onEnd = false) {
  if (onEnd) {
    return Number(value).toFixed(2) + symbol;
  }
  return symbol + Number(value).toFixed(2);
}

console.log(toCurrency(123.7483));
console.log(toCurrency(123));
console.log(toCurrency(123, ' USD', true));
zb'
  • 8,071
  • 4
  • 41
  • 68