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.96k stars 530 forks source link

Zero can't be formatted #139

Open firedev opened 8 years ago

firedev commented 8 years ago
const accounting = require('accounting')
const value = 0

accounting.formatMoney(
  value, {
    symbol: '%',
    format: {
      pos: '%v%s',
    }})

Expected:

0%

Actual:

node_modules/accounting/accounting.js:307
        return useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(number), checkPrecision(opts.precision), opts.thousand, opts.decimal));
                        ^

TypeError: Cannot read property 'replace' of undefined
    at Object.lib.formatMoney (/Users/pain/Sites/sr/apps/node_modules/accounting/accounting.js:307:19)
    at Object.<anonymous> (/Users/pain/Sites/sr/apps/src/test.js:4:12)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:142:18)
    at node.js:939:3

Works if the value is not 0

in15 commented 8 years ago

Hey @firedev. Were you able to find a solution? Running into something similar now

goferito commented 7 years ago

+1 here. I had to handle 0 to avoid formatting it with this library. I think the solution is pretty easy though, but maintainers don't seem to accept PRs anymore.

firedev commented 7 years ago

Hey @in15, sorry, I just handle zeros manually.

garmr commented 6 years ago

Sorry to resurect old thread but I've just ran into this issue. After reviewing the code it appears that zero needs its own special format to avoid this issue.

accounting.settings = {
    currency: {
        symbol : "€",   // default currency symbol is '$'
        format: {
            pos : "%v&nbsp;%s",
            zero : "%v&nbsp;%s"
        }, // controls output: %s = symbol, %v = value/number (can be object: see below)
        decimal : ",",  // decimal point separator
        thousand: " ",  // thousands separator
        precision : 2,   // decimal places
    },
    number: {
        precision : 0,  // default precision on numbers is 0
        thousand: " ",
        decimal : ","
    }
};

please note the zero : "%v&nbsp;%s" index under format.

This solved this issue at least in my specific case.