Search code examples
javascriptjsrender

How to format decimal using JsRender templates


i am using JsRender templates in my cshtml page. I have some decimal values in my data and want to show 2 numbers afer comma like 17,89 or 3,00. When i have 3 in my data it show only 3 in my template.

How can i format my decimal data?

Just a little example from my template that show how i use data {{>rate}}

Thanks


Solution

  • If rate is guaranteed to be a number, you can use JavaScript toFixed() like this:

    {{:rate.toFixed(2)}}
    

    If rate could be a string, you can coerce it to number, by writing

    {{:(+rate).toFixed(2)}}
    

    If you want to make a better separation of code and markup, you can define a converter:

    $.views.converters("dec",
      function(val) {
        return (+val).toFixed(2);
      }
    );
    

    And then write:

    {{dec:rate}}
    

    You can even make the converter smart, and accept a places=n property, to configure the number of decimal places:

    $.views.converters("dec",
      function(val) {
        return (+val).toFixed(this.tagCtx.props.places || 2);
      }
    );
    

    then optionally specify the number of decimal places:

    {{dec:rate places=3}}