KendoUI: Formatting Dates, Numbers, Currency and Custom Formats

Ever need to format text in JavaScript?  Ok, dumb question.  Everyone has needed that functionality.  Well, if you use KendoUI, Telerik provides a pretty awesome framework for this.  There is a toString method which is documented here.

This method takes three parameters:

  • value –> the Date or Number to be formatted.
  • format –> string to format.
    • n –>  Format as a Number.  If you include a number after the n, then this will denote the number of decimal places.
    • p –> Format as a Percent
    • c –> format as the Currency including the symbol
    • date format like ‘yyyy/MM/dd’
    • Custom Formatter like ’00##’
  • culture –> the name of the culture which should be used to format the value.  If this parameter is not supplied, then the default culture is used

Now, this is pretty AWESOME.  Lets say you need to display a value in multiple currencies and formatted for each currency.

In your page, you need to register each KendoUI culture script.  For this example, let’s reference the following:

<script src="http://cdn.kendostatic.com/2013.2.716/js/cultures/kendo.culture.de-DE.min.js"></script>
<script src="http://cdn.kendostatic.com/2013.2.716/js/cultures/kendo.culture.sv-SE.min.js"></script>
<script src="http://cdn.kendostatic.com/2013.2.716/js/cultures/kendo.culture.en-US.min.js"></script>

You also need a reference to kendo.core.js.

Now, that you are referencing the cultures you need,  it is pretty easy to format your dates and string in JavaScript.

For instance:

kendo.toString(1234.23, ‘c’, ‘de-DE’)  –>   1.234,23 €

kendo.toString(1234.23, ‘c’, ‘sv-SE’)  –> 1.234,23 kr

kendo.toString(1234.23, ‘c’, ‘en-US’)  –> $1,234.23

This is pretty slick.  You can format the currency based on a culture which comes in very handy in some business application where you might need to display multiple currencies on the same page.

Other places to use this:

  • In a ClientTemplate on a column on a Grid so you could format one column for Swiss Franc then have another column for US Dollars.
  • For formatting date time when displaying multiple dates for more than one culture
  • Allowing the user to pick a culture and dynamically update the formats of the numbers, dates, etc without reposting the page.

 

 

 

 

 

2 thoughts on “KendoUI: Formatting Dates, Numbers, Currency and Custom Formats

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s