diff --git a/src/math/calculation.js b/src/math/calculation.js index bda2a25544..7bc94ea85b 100644 --- a/src/math/calculation.js +++ b/src/math/calculation.js @@ -694,7 +694,8 @@ p5.prototype.round = function(n, decimals) { if (!decimals) { return Math.round(n); } - return Number(Math.round(n + 'e' + decimals) + 'e-' + decimals); + const multiplier = Math.pow(10, decimals); + return Math.round(n * multiplier) / multiplier; }; /** diff --git a/test/unit/math/calculation.js b/test/unit/math/calculation.js index 8ec1d05ec1..72d6cfe93e 100644 --- a/test/unit/math/calculation.js +++ b/test/unit/math/calculation.js @@ -425,6 +425,16 @@ suite('Calculation', function() { result = myp5.round(12.31833, 2); assert.equal(result, 12.32); }); + + test('should round very small numbers to zero', function() { + result = myp5.round(1.234567e-14); + assert.equal(result, 0); + }); + + test('should round very small numbers to zero when decimal places are specified', function() { + result = myp5.round(1.234567e-14, 2); + assert.equal(result, 0); + }); }); suite('p5.prototype.sqrt', function() {