- Was specifically purposed for dealing with numeric values
- Handled the parsing / formatting for the current locale (and I naturally intended to use Globalize for this purpose)
Essentially his approach provides an “interceptor” mechanism that allows you to validate numeric data entry on input and format numeric data going out as well. Very nice. Into this I plugged Globalize to handle the parsing and formatting. I ended up with the “valueNumber” binding handler:
Using this binding handler you just need to drop in a
valueNumber into your
data-bind statement where you might previously have used a
value binding. The binding also has a couple of nice hooks in place which you might find useful:
- numberFormat (defaults to "n2")
- allows you to specify a format to display your number with. Eg, "c2" would display your number as a currency to 2 decimal places, "p1" would display your number as a percentage to 1 decimal place etc
- isNullable (defaults to false)
- specifies whether your number should be treated as nullable. If it's not then clearing the elements value will set the underlying observable to 0.
Finally when the element gains focus / becomes active the full underlying value is displayed. (Kind of like Excel - like many an app, the one I'm working on started life as Excel and the users want to keep some of the nice aspects of Excel's UI.) To take a scenario, let's imagine we have an input element which is applying the "n1" format. The underlying value backing this is 1.234. The valueNumber binding displays this as "1.2" when the input does not have focus and when the element gains focus the full "1.234" is displayed. Credit where it’s due, this is thanks to Robert Westerlund who was kind enough to respond to a question of mine on StackOverflow.
Finally, here’s a demo using the "de-DE" locale:
The version of Globalize used in the binding handler is Globalize v0.1.1. This has been available in various forms for quite some time but as I write this the Globalize plugin is in the process of being ported to the CLDR. As part of that work it looks like the Globalize API will change. When that gets finalized I’ll try and come back and update this.