From 7e72a4d79dff125867cfc0acc7a014f346d652cc Mon Sep 17 00:00:00 2001 From: Fedor Indutny Date: Thu, 15 May 2014 02:59:07 +0400 Subject: [PATCH] utils: `toBTC()` --- lib/bcoin/utils.js | 18 ++++++++++++++++-- test/utils-test.js | 10 ++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/lib/bcoin/utils.js b/lib/bcoin/utils.js index e8cf23d8..f09e9596 100644 --- a/lib/bcoin/utils.js +++ b/lib/bcoin/utils.js @@ -365,9 +365,23 @@ utils.revHex = function revHex(s) { utils.assert = function assert(val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); -} +}; utils.assert.equal = function assertEqual(l, r, msg) { if (l != r) throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); -} +}; + +utils.toBTC = function toBTC(satoshi) { + var m = new bn(10000000).mul(new bn(10)); + var lo = satoshi.mod(m); + if (lo.cmpn(0) !== 0) { + lo = lo.toString(10); + while (lo.length < 8) + lo = '0' + lo; + lo = '.' + lo; + } else { + lo = ''; + } + return satoshi.div(m).toString(10) + lo.replace(/0+$/, ''); +}; diff --git a/test/utils-test.js b/test/utils-test.js index d0371998..d5fa8320 100644 --- a/test/utils-test.js +++ b/test/utils-test.js @@ -1,4 +1,5 @@ var assert = require('assert'); +var bn = require('bn.js'); var bcoin = require('../'); describe('Utils', function() { @@ -18,4 +19,13 @@ describe('Utils', function() { var target = bcoin.utils.bitsToTarget(bits); assert(bcoin.utils.testTarget(target, hash)); }); + + it('should convert satoshi to btc', function() { + var btc = bcoin.utils.toBTC(new bn(5460)); + assert.equal(btc, '0.0000546'); + var btc = bcoin.utils.toBTC(new bn(54678).mul(new bn(1000000))); + assert.equal(btc, '546.78'); + var btc = bcoin.utils.toBTC(new bn(5460).mul(new bn(10000000))); + assert.equal(btc, '546'); + }); });