JS两个小数位.toFixed(2)

时间:2018-02-20 19:40:47

标签: javascript

.toFixed在我的代码中不起作用。我正在使用.toLocaleString()

JS /小提琴:https://jsfiddle.net/8b6t90f5/

$(function() {
  var value = 5000.3269588;


  $("#process").click(function() {

    $('#amount').text("Total: $" + value.toLocaleString().toFixed(2));

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="amount"></div>

<input id="process" class="button_text" type="submit" name="submit" value="SHOW VALUE">

3 个答案:

答案 0 :(得分:1)

字符串没有toFixed(),只有数字。

      $('#amount').text("Total: " + value.toLocaleString("en-US", {maximumFractionDigits:2, currency:"USD", style:"currency"})); 

可能就是你所追求的。

答案 1 :(得分:0)

toFixed()是一种Number方法。 toLocaleString()将其变为字符串。您需要先使用toFixed(),然后将其解析为浮动并使用toLocaleString()

parseFloat(value.toFixed(2)).toLocalString('en-BR');

&#13;
&#13;
const num = 50023.357289357;
console.log(parseFloat(num.toFixed(2)).toLocaleString());
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

您继续对数字使用字符串方法,反之亦然。试试这个:

const num = 5000.3269588;
console.log(num.toLocaleString(undefined, {maximumFractionDigits: 2}));