14.8. String Conversions and Value Formatting
A 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 Times
14.8.2. Formatting Numbers
MochiKit.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 Functions
MochiKit includes the following additional simple functions for formatting values.