Skip to content
This repository has been archived by the owner on Apr 3, 2019. It is now read-only.

Commit

Permalink
Merge pull request #45 from isocolsky/format_number
Browse files Browse the repository at this point in the history
Improve amount formatting
  • Loading branch information
isocolsky committed Mar 27, 2015
2 parents f0eb46d + 18bbd5c commit b9763cd
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 25 deletions.
18 changes: 4 additions & 14 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,6 @@ var $ = require('preconditions').singleton();

var Utils = {};

var _SEPARATORS = {
en: {
thousands: ',',
decimal: '.'
},
es: {
thousands: '.',
decimal: ','
},
};
var _UNITS = {
btc: {
toSatoshis: 100000000,
Expand All @@ -26,10 +16,9 @@ var _UNITS = {
},
};

Utils.formatAmount = function(satoshis, unit, locale) {
Utils.formatAmount = function(satoshis, unit, opts) {
$.shouldBeNumber(satoshis);
$.checkArgument(_.contains(_.keys(_UNITS), unit));
$.checkArgument(_.contains(_.keys(_SEPARATORS), locale));

function addSeparators(nStr, thousands, decimal) {
nStr = nStr.replace('.', decimal);
Expand All @@ -40,10 +29,11 @@ Utils.formatAmount = function(satoshis, unit, locale) {
return x1 + x2;
}

opts = opts || {};

var u = _UNITS[unit];
var l = _SEPARATORS[locale];
var amount = (satoshis / u.toSatoshis).toFixed(u.decimals);
return addSeparators(amount, l.thousands, l.decimal);
return addSeparators(amount, opts.thousandsSeparator || ',', opts.decimalSeparator || '.');
};

module.exports = Utils;
29 changes: 18 additions & 11 deletions test/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,35 +12,42 @@ describe('Utils', function() {
describe('#formatAmount', function() {
it('should successfully format amount', function() {
var cases = [{
args: [1, 'bit', 'en'],
args: [1, 'bit'],
expected: '0',
}, {
args: [1, 'btc', 'en'],
args: [1, 'btc'],
expected: '0.000000',
}, {
args: [0, 'bit', 'en'],
args: [0, 'bit'],
expected: '0',
}, {
args: [12345678, 'bit', 'en'],
args: [12345678, 'bit'],
expected: '123,457',
}, {
args: [12345678, 'btc', 'en'],
args: [12345678, 'btc'],
expected: '0.123457',
}, {
args: [12345611, 'btc', 'en'],
args: [12345611, 'btc'],
expected: '0.123456',
}, {
args: [1234567899999, 'btc', 'en'],
args: [1234567899999, 'btc'],
expected: '12,345.679000',
}, {
args: [12345678, 'bit', 'es'],
args: [12345678, 'bit', {
thousandsSeparator: '.'
}],
expected: '123.457',
}, {
args: [12345678, 'btc', 'es'],
args: [12345678, 'btc', {
decimalSeparator: ','
}],
expected: '0,123457',
}, {
args: [1234567899999, 'btc', 'es'],
expected: '12.345,679000',
args: [1234567899999, 'btc', {
thousandsSeparator: ' ',
decimalSeparator: ','
}],
expected: '12 345,679000',
}, ];

_.each(cases, function(testCase) {
Expand Down

0 comments on commit b9763cd

Please sign in to comment.