4

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'
leppie
  • 115,091
  • 17
  • 196
  • 297
Warlock
  • 7,321
  • 10
  • 55
  • 75
  • 1
    The stuff inside `<%= ... %>` is just a JavaScript expression so I think you're really just looking for [JavaScript equivalent to printf/string.format](http://stackoverflow.com/q/610406/479863). [underscore.string](https://github.com/epeli/underscore.string) is an Underscore mixin that provides most of what you need and nicely meshes with Underscore. – mu is too short Nov 25 '14 at 07:25

1 Answers1

7

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>
Eugene Naydenov
  • 7,165
  • 2
  • 25
  • 43