Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format numbers in underscore template?

I have an expression in my underscore template like this:

'<%= a %> div <%= b %> is <%= a/b %>'

I would like to limit the number of decimal counts to a specific number. Is it possible in underscore.js?

Expected:

'10 div 3 is 3.33'

but actually I see:

'10 div 3 is 3.333333333'
like image 646
Warlock Avatar asked Mar 18 '23 19:03

Warlock


1 Answers

Just use 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);
<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>
like image 136
Eugene Naydenov Avatar answered Apr 07 '23 09:04

Eugene Naydenov