圆形功能并添加" $"

时间:2017-07-18 04:04:44

标签: javascript html

我已多次搜索并尝试但仍无法获得。我如何前置" $"并将值四舍五入到最接近的十进制小数。示例:$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>

1 个答案:

答案 0 :(得分:2)

使用Number.prototype.toFixed()来生成固定数量的小数,像往常一样连接字符串,因为toFixed返回字符串:

&#13;
&#13;
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));
&#13;
&#13;
&#13;