From 2cff305f462da53a681bc47a84e77e3abd991335 Mon Sep 17 00:00:00 2001 From: Chris Troutner Date: Sat, 13 Feb 2021 14:59:33 -0800 Subject: [PATCH] feat(floor2): bchjs.Util.floor2(num) - round down to 2 decimal places --- src/util.js | 35 +++++++++++++++++++++++++++++++++++ test/unit/util.js | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/src/util.js b/src/util.js index 441480d..d8fc064 100644 --- a/src/util.js +++ b/src/util.js @@ -62,6 +62,41 @@ class Util { return tempNum } + /** + * @api util.floor2() floor2() + * @apiName floor2 + * @apiGroup Util + * @apiDescription Round a number down to 2 decimal places. + * + * + * @apiExample Example usage: + * (async () => { + * try { + * const num = 1.234567891111 + * const result = bchjs.Util.floor2(num) + * console.log(result) + * } catch(error) { + * console.error(error) + * } + * })() + * + * // returns + * 1.23 + */ + // floor2 - round down to 2 decimal places + // Takes a number and returns it, rounded to the nearest 2 decimal place. + floor2 (num) { + const thisNum = Number(num) + + if (isNaN(thisNum)) throw new Error('input must be a number') + + let tempNum = thisNum * 100 + tempNum = Math.floor(tempNum) + tempNum = tempNum / 100 + + return tempNum + } + /** * @api util.validateAddress() validateAddress() * @apiName Validate Address. diff --git a/test/unit/util.js b/test/unit/util.js index 55562e0..09ffcaa 100644 --- a/test/unit/util.js +++ b/test/unit/util.js @@ -66,4 +66,37 @@ describe('#Util', () => { assert2.equal(result, 1.23) }) }) + + describe('#floor2', () => { + it('should round a number to 2 decimals', () => { + const num = 1.234567891111 + + const result = bchjs.Util.floor2(num) + // console.log(result) + + assert2.equal(result, 1.23) + }) + + it('should throw an error for non-number input', () => { + try { + const num = 'string' + + bchjs.Util.floor2(num) + + assert2.equal(true, false, 'Unexpected result') + } catch (err) { + // console.log(err) + assert2.include(err.message, 'input must be a number') + } + }) + + it('should not effect a number with less than 8 decimals', () => { + const num = 1.2 + + const result = bchjs.Util.floor2(num) + // console.log(result) + + assert2.equal(result, 1.2) + }) + }) })