diff --git a/src/dinero.js b/src/dinero.js index 0acde4533..ca917b17a 100644 --- a/src/dinero.js +++ b/src/dinero.js @@ -493,6 +493,20 @@ const Dinero = options => { toUnit() { return this.getAmount() / 100 }, + /** + * Returns the amount represented by this object in rounded units. + * + * @example + * // returns 10.6 + * Dinero({ amount: 1055 }).toRoundedUnit(1) + * + * @param {Number} precision - The number of fraction digits to round to. + * @return {Number} + */ + toRoundedUnit(precision) { + const factor = Math.pow(10, precision) + return Math.round(this.toUnit() * factor) / factor + }, /** * Return the object's data as an object literal. * diff --git a/test/unit/dinero.spec.js b/test/unit/dinero.spec.js index 4e60382a9..a9763d23c 100644 --- a/test/unit/dinero.spec.js +++ b/test/unit/dinero.spec.js @@ -330,6 +330,11 @@ describe('Dinero', () => { expect(Dinero({ amount: 1050 }).toUnit()).to.equal(10.5) }) }) + describe('#toRoundedUnit()', () => { + it('should return the amount divided by 100, rounded to one fraction digit', () => { + expect(Dinero({ amount: 1055 }).toRoundedUnit(1)).to.equal(10.6) + }) + }) describe('#toObject()', () => { it('should return an object literal with the right data', () => { expect(Dinero({ amount: 500, currency: 'EUR' }).toObject()).to.deep.equal(