openexchangerates / accounting.js

A lightweight JavaScript library for number, money and currency formatting - fully localisable, zero dependencies.
http://openexchangerates.github.io/accounting.js
MIT License
4.95k stars 532 forks source link

Robust method of formatting values #17

Closed wjcrowcroft closed 12 years ago

wjcrowcroft commented 13 years ago

accounting.js currently uses a simple format string to figure out where to place the value and the currency symbol, but it needs a bit more thought for future development, to make sure as many potential permutations are covered as possible and the most common is provided as a default. This will also pave the way for more complex i18n methods/plugins later on.

Current method of formatting, propose to keep for the time being:

var settings = {
    currency : {
        format : "%s %v", // %s = symbol, %v = formatNumber(value); spaces/other characters are preserved
        thousand : ",",   // default thousand separator is a comma
        decimal : ".",    // default decimal separator is a dot
        precision : 2,    // default precision is 2 decimal places
        grouping : 3      // default digit-grouping is 3 digits eg. 1,000,000 (not implemented)

Proposed formatting method for v0.2:

var settings = {
    currency : {
        format : {
            default : "%s %v",
            negative : "%s -%v", // default eg. "$ -1.00" but could be eg. "%s (%v)" for "$ (1.00)"
            zero : " - "         // optional format for when value === 0
        },
        // Or just a string, in which case negative format is `format.replace("%v", "-%v")`:
        format : "%s %v" // 

        // other values same as above

formatColumn still needs to know more explicitly where to place the padding in order to line up money values, so for that I'd propose a simple rule, along the lines of: _padding always inserted _after* %s (symbol) in format, unless there is no %s, or %s comes after %v, in which case padding is inserted at index 0*

The only change for v0.1 would be to implement the grouping parameter if possible, for locales where default digit-grouping is not 3 (not urgent) and to create a helper method to parse format, that creates a negative format based on the format, to prepare for the changes in v0.2.


For later versions in the coming months, I'd like to look at Google Closure Library numberformat.js which has a pretty full-featured approach to formatting and localising.

I think the way forward is to keep the native number/currency formatting methods in the library relatively simple (eg you can control the symbol, the separators, the grouping/precision, negatives, and the basic format string) and then provide a more fully-featured formatting plugin, for advanced use cases.

If anyone has any thoughts, discuss it here!