GithubHelp home page GithubHelp logo

openexchangerates / accounting.js Goto Github PK

View Code? Open in Web Editor NEW
4.9K 4.9K 529.0 248 KB

A lightweight JavaScript library for number, money and currency formatting - fully localisable, zero dependencies.

Home Page: http://openexchangerates.github.io/accounting.js

License: MIT License

CSS 4.56% JavaScript 78.99% HTML 16.45%

accounting.js's People

Contributors

fmntf avatar gustavlrsn avatar jasonpberry avatar jjsquillante avatar joeljuca avatar keithpitt avatar maiwald avatar mcordingley avatar millermedeiros avatar mrmoses avatar reiz avatar ryanwood avatar wbotelhos avatar wjcrowcroft avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

accounting.js's Issues

in place formatting

Is it possible to do formatting on the text field in place? So as I am typing, it will add the commas.

Is there a sample/demo already available or do I have to implement it myself using the .bind?

create unit tests

Unit tests are essential to avoid regressions and to help spotting edge cases.

Add option for rounding method

Rounding should be an option - always up, always down, or [default] nearest neighbour.

Can anybody weigh in on what the options for rounding would be labelled? floor and ceil possibly don't apply since they imply rounding up/down to integers, but rounding in our case also applies to floating points, eg 0.615 > 0.62

Any thoughts, do share. Cheers

Add an IsValidNumber function

Hi, I love this library and it's been really helpful to me on a recent project. One suggestion: could you add a routine to determine if a string will be parsed correctly by "unformat". Something like "isValidNumber( string )". Alternatively, unformat could return null or undefined for invalid input instead of 0. I need to light up invalid text boxes in my application, so I need to be able to tell the difference between invalid and 0.

Thanks again for the really excellent library!

formatNumber fails after many runs in chrome

I ran in to a really strange bug

var largeNumber = 2749606250;
var expected = '2,749,606,250';
var result;

for (var i = 0; i < 1000; i++) {
    result = accounting.formatNumber(largeNumber);
    if (result != expected) {
        console.log('failed at', i, result);
        break;
    }
}

console.log('done', result);

// failed at 393 1,545,361,046
// done 1,545,361,046 

After ~400 runs the result becomes wildly inaccurate. I can only reproduce in chrome so it might be some optimizer bug. (tested nodejs 0.8 and firefox 13, both chrome stable and beta fails)

Here's a jsfiddle that can reproduce it in chrome: http://jsfiddle.net/nSavd/3/

Large numbers formatted incorrectly in IE8

var number = accounting.formatNumber(10000000000000000000000000000000000000/184.77, 2);
// (IE8)   number = "5,.406,574,394,463,668,5e+34.00"
// (Other) number = "5.4065743944636685e+34"

In formatNumber, the base resolves to "5.4065743944636685e+34" and the decimal resolves to "00".

This is due to Number.prototype.toFixed returning "54065743944636685000000000000000000.00", which then the base pulls out the full integer before returning it as scientific notation. I was under the impression that all of the browser implementations of toFixed properly displayed scientific notation when > 1e21.

Number.prototype.toString is properly returning "5.406574394463668e+34".

Is this simply a known issue/limitation of IE8? Or is there a workaround?

Formatting the Negative number like MS Excel

Hi,

Very nice and light weight JS plugin for formatting the currencies!!

But however I am looking to extend this plugin to suit one of my requirement:

  • When I format a negative amount i.e.
    account.formatMoney(-100000) = $(100,000.00), but I am looking to have it the way MS Excel does i.e like this ($100,000.00).
    Kindly let me know where I have to modify the js file.

Typos by End User

There is an issue I noticed. If an end user types in 350t, the script converts it to $350.00. This can cause issues because maybe the customer wanted to type in 3505, and the number should be $3,505.00....IMO, the script should kick out a NULL or 0. Im doing a calculator and accounting.js just keeps plugging away so long as there are SOME numbers from the end user....even if its text first.....such as thisshouldntwork350.....will get formatted to $350.00.

Thanks for a great script!

Add to bower

Hey, loving your library, would you mind adding it to bower?

http://twitter.github.com/bower/

All you need to do is run this command in your project root:

bower register accounting git://github.com/josscrowcroft/accounting.js

Then it should be possible to install with:

bower install accounting

Bower should use your package.json to find the right file to download, but if you want to get more specific you could add this component.json file to the root of your project:

{
  "name": "accounting",
  "version": "0.3.2",
  "main": "accounting.js"
}

Cheers!

Add adapter plugin for jQuery

An adapter for jQuery would be rad - enabling you to specify $('#el').formatMoney() to format numbers in a given element.

Definitely implemented as a plugin/add-on as I want to keep the library dependency-free.

Any thoughts, please share them here!

Feature suggestion

it will be great if it this library directaly detect the locale according to i18 and set the options according to same. just like jquery i18 library.

missing default "$" on formatNumber()

I include the latest js (not minified) and call accounting.formatNumber( 1234 ).
I get "1,234" but I was expecting "$ 1,234".
I also tried adding a { symbol: "$" } after the 1234 but I keep getting the same string.

Ability to specify 'zero' value for currency, eg. " - "

In some accounting systems (and excel formatting), zero values are given as -, eg:

$ 1,000,000
$     1,100
$        -

This would be given in the settings, eg:

currency: {
    zero: " - "
}

Implementing this would mess with formatColumn in its current state, but that method will probably be rewritten soon to make it more robust.

Publish this library in NPM

Hello,

It would be great to have this library published in NPM so it can be easier to use it in NodeJS projects.

Unformat makes bracket-notation negatives become positives

Not so much a 'bug' as a 'huh?'

If you're formatting negative values with brackets, which is common in financial and accounting scenarios, accounting.unformat should recognise them. Currently:

accounting.unformat( "GBP (53,180.08)" ) // 5318008 (should be -5318008)

But this could definitely get confusing for people if not done properly and requires a pretty solid regular expression and good documentation, otherwise it'll become one of those things that people constantly say "Hey man wtf" because they weren't aware of that behaviour.

License change

Any chance you might relicense under a less restrictive license like MIT/BSD?

Skip for null input values

Could the code check for null values?

At the moment a null value is treated as a zero, which can be misleading:

// Choose which format to use for this value (pos, neg or zero):
var useFormat = val > 0 ? formats.pos : val < 0 ? formats.neg : formats.zero,

I can work around this by checking for null before calling the method, but would be nice to handle it within accounting.js.

Thanks,

Steve

Numbers entered with custom decimal get returned 100x higher (separators placed at wrong places)

In using accounting.js, I noticed something strange when using a custom decimal separator (the European-style comma).

The following code sample runs accounting.formatNumber() on two <input>-fields to format their values (which works fine). Clicking a textbox will replace the value with the unformat()-ed number (which works fine). However, when I change the value by typing a value such as 64,00 (comma included) and call formatNumber(), the result will have the decimal/thousand-separators placed in the wrong place (6.400,00).

The number is correctly formatted according to the preferences... only it's 100 times the original value ;)

I have set up an example here:
http://jsfiddle.net/erlingormar/qp7mz/12/

Add support for number calculations

Apologies if this is just showing my Javascript noob-ness, but I am looking for a way to add/multiply money figures and still get money afterwards.

For example, if I have:

var a = 36.33;
a*36 // gives 1307.87999999 rather than 1307.88

Is this something that perhaps fits with this library - ie would it be a valid enhancement it to provide support for money calculations? (Or have you seen a library for this?)

Thanks in advance,
Chris

currency symbol position option

Please add another option for formatting: currency symbol position - "before" (default) and "after" the number ($123 vs 123$).
Example:


Robust method of formatting values

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!

Rounding

The rounding is inconsistent. 0.615 gets rounded to 0.61.

Suggestion: You also might want to specify the rounding method: Normal mathematical rounding (round 0.5 away from 0) and bankers' rounding (round 0.5 to nearest even number) which is more often used in accounting. You might even go crazy and ask for the rounding radix...

Allow creating "instances" of accounting

Instead of providing "static" functions, it would be awesome if we could create instances of accounting, like this:

var dolar = new Accounting({
   currency: {
      symbol: "$"
   }
});

var euro = new Accounting({
   currency: {
      symbol: "€"
   }
});

This can prevent lots of duplication in applications that work with different formats throughout the code. For instance, suppose your application works with several different precisions. You actually have to inform the precision argument in every call to accounting.formatNumber(), hence duplicating the precision argument:

// Some context
accounting.formatNumber(foo, 3);
accounting.formatNumber(bar, 3);

// Another context
accounting.formatNumber(bar, 5);
accounting.formatNumber(zaz, 5);

// Yet another context
accounting.formatNumber(zaz, 2);
accounting.formatNumber(foo, 2);

By creating one instance of Accounting for each context, we could avoid the duplication of the precision argument:

var someContext = new Accounting({ number: { precision: 3 } });
var anotherContext = new Accounting({ number: { precision: 5 } });
var yetAnotherContext = new Accounting({ number: { precision: 2 } });

someContext.formatNumber(foo);
someContext.formatNumber(bar);

anotherContext.formatNumber(bar);
anotherContext.formatNumber(zaz);

yetAnotherContext.formatNumber(zaz);
yetAnotherContext.formatNumber(foo);

There are, of course, other ways to remove that kind of duplication, but I think that the most convenient/modular way is to create an Accounting "class" (or prototype).

AMD module loading do not seems to work

We are using accounting 0.3.2 with requirejs 2.0.6: accounting is properly loaded but it is not accessible like Underscore or Backbone.

Replacing the last lines of the script with those used in Underscore.js makes everything work:

if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
        exports = module.exports = lib;
    }
    exports.accounting = lib;
} else {
        root.accounting = lib;
}

IE Testing & Bug Fixing

Need to do some rigorous IE testing for the current code and the 0.1.4 version currently on the dev branch.

If anyone finds and bugs in IE, please use this thread for them.

Automatically detect decimal and thousand separator

You could automatically detect the client's regional settings:

var accounting_number = 1.1;
accounting_number = accounting_number.toLocaleString().substring(1,2);
if(accounting_number != '.') {
accounting.settings.currency.decimal = ',';
accounting.settings.currency.thousand = '.';
}

format an already formatted value breaks

maybe this is intended behaviour, but formatting an already formatted value returns a wrong value.

accounting.formatMoney("1.200,33", {
    symbol: "",
    precision: 2,
    thousand: ".",
    decimal : ",",
});

output is: "1,20". instead, this should return "1.200,33" ... right?

Global configuration for currency formatting ('Currency != Number format')

Currency is not the same thing as number format and therefore I propose to you that they be treated seperately, hopefully using some sort of locale identifier.

Being from the UK, I prefer numbers in the following format: 123,456.78

Viewing a price in EUR € doesn't mean I would like the numbers displayed as 123.456,78

Zend Framework has an implementation you may find helpful to review:
http://framework.zend.com/manual/en/zend.locale.parsing.html#zend.locale.number.localize

toFixed error

I got this:

accounting.toFixed(35.175,2)
"35.17"

I should be getting 35.18, right?

I need the symbol on the right side

Hi,

I am working on a project with Turkish currency.

It appears as though the symbol for the Lira, TL, appears on the right side of the quantity:

eg) 6.582,04 TL

Is there a specific settings property I can apply to achieve this display?

Any help and direction you can offer is greatly appreciated.

Thank you for a useful library.

All the best,

Ben

Format negative values

If I use accounting with a negative value I get $-5.00 instead of -$5.00 which appears to be the standard way of displaying negative currency

Force specific string length in formatColumn (appending new values to existing column)

When new rows are added to a column in a table/list of values that has been formatted with formatColumn it would be great if the added values could be column-formatted along with the preceding values, otherwise this happens:

$     1
$    23
$ 4,567
$ 890   // this one was appended but not column-formatted

Specifying an option (eg. minLength : 7), which pads the string to that length, might be one way to tackle this.

A slightly more complicated alternative - could pass in a value or array of values to match it up to, for example:

var column = ["$     1", "$    23", "$ 4,567"];

accounting.formatColumn( [890], {
    join : column
});
// --> "$   890"

Or a combination of the two.

If anyone has ideas - please add.

Create plugin for l10n formatting information

On Forrst, Jan-Marten de Boer (johmanx10) pointed to a script he wrote that returns a JSON-representation of a country's localisation data - currency symbol, number formatting, etc. - for example: http://lievheid.nl/assets/langinfo/nl/nl/utf8

Since the data doesn't change much and could realistically be bundled into one script, with no AJAX request necessary, the idea was raised about it being turned into a plugin that can work with accounting.js to give developers access to a country's localisation style, or the ability to set a locale and have the defaults set automatically.

This (and other plugin ideas) relies on making a very simple plugin architecture for accounting.js, and making a library configuration object that the plugin could interface with to control the formatting

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.