我的下划线模板中有一个表达式,如下所示:
'<%= a %> div <%= b %> is <%= a/b %>'
我想将小数计数限制为特定数字。是否有可能在underscore.js?
预期:
'10 div 3 is 3.33'
但实际上我看到了:
'10 div 3 is 3.333333333'
答案 0 :(得分:7)
只需使用Number.prototype.toFixed()
:
<%= a %> div <%= b %> is <%= (a/b).toFixed(2) %>
var tpl, content;
tpl = $('#division-tpl').html();
content = _.template(tpl)({a: 10, b: 3, digits: 2});
$('#content').html(content);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script type="text/template" id="division-tpl">
<%= a %> div <%= b %> is <%= (a/b).toFixed(digits) %>
</script>
<div id="content"></div>
&#13;