Search code examples
formattingunderscore.jsunderscore.js-templating

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'

Solution

  • 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>