14.8. String Conversions and Value FormattingA common need in any software is to convert values between machine-maintained formats and human-understandable ones. MochiKit provides some of the most commonly required functions for working with dates and formatting numeric values as strings. 14.8.1. Working with Dates and TimesJavaScript has a handy Date object for keeping track of dates and times. Unfortunately, however, when you make an Ajax request to a server, that server isn't going to understand that Date object (even if you could find a way to directly send it!). And you're not going to get a JavaScript date back from the server. MochiKit.DateTime provides a set of functions for converting dates between JavaScript and the rest of the world. To get a JavaScript Date object, use one of the following functions:
To convert a JavaScript Date object for use externally, use one of the following functions:
14.8.2. Formatting NumbersMochiKit.Format provides useful string formatting functions, including a powerful number formatter. No one likes to see a number such as 483483232 on a web page, although people in different countries might argue about what the proper way to display that number is. In the United States, we'd like that number to be formatted as 483,483,232. Here's how we do that with MochiKit: >>> f = numberFormatter("#,###") ("#,###") >>> f(483483232) "483,483,232" numberFormatter(pattern, placeholder="", locale="default") returns a function that will format a number according to the pattern. If you provide a placeholder and the value presented for formatting isn't a number, you'll get that placeholder back. The locale can be a known locale (en_US, de_DE, fr_FR, etc.) or an object with separator (the "thousands" separator), decimal (the decimal separator), and percent (the symbol for a percent). The pattern, of course, is the most interesting part of the numberFormatter call. For displaying numbers, MochiKit uses the following special characters:
Note that you'll actually get the locale-specific characters rather than ",", "." and "%" in the final, formatted string. Here are some more examples to show off usage of the formatter: >>> numberFormatter("USD $#,###.00")(15) "USD $15.00" >>> numberFormatter("#,### %")(0.75) "1 %" >>> numberFormatter("#,### %")(75) "75 %" >>> numberFormatter("#,###%")(75) "7,500%" >>> numberFormatter("0,000")(75) "0,075" >>> numberFormatter("##,##")(7534) "75,34" You can see from the middle examples that the position of the % sign makes a difference in whether MochiKit treats the number as a percentage. 14.8.3. Other String Formatting FunctionsMochiKit includes the following additional simple functions for formatting values.
|