From 7a724aa4299c8ace762352d7876f1dad1d9082b5 Mon Sep 17 00:00:00 2001 From: Dror Weiss <> Date: Wed, 19 Apr 2023 15:46:24 +0300 Subject: [PATCH 1/3] Fix 1.0 not recognized as float --- lib/accessors/float.js | 2 +- test/index.js | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/accessors/float.js b/lib/accessors/float.js index cb3514a..80921fd 100644 --- a/lib/accessors/float.js +++ b/lib/accessors/float.js @@ -3,7 +3,7 @@ module.exports = function asFloat (value) { const n = parseFloat(value) - if (isNaN(n) || n.toString() !== value) { + if (isNaN(n) || isNaN(value)) { throw new Error('should be a valid float') } diff --git a/test/index.js b/test/index.js index f643e5f..112372a 100644 --- a/test/index.js +++ b/test/index.js @@ -12,6 +12,7 @@ describe('env-var', function () { INVALID_BASE_64: 'a|GV-sb*G8=', STRING: 'oh hai', FLOAT: '12.43', + FLOAT_INTEGER: '1.0', INTEGER: '5', BOOL: 'false', JSON: '{"name":"value"}', @@ -227,6 +228,7 @@ describe('env-var', function () { it('should return a float', function () { expect(mod.get('FLOAT').asFloat()).to.be.a('number') expect(mod.get('FLOAT').asFloat()).to.equal(parseFloat(TEST_VARS.FLOAT)) + expect(mod.get('FLOAT_INTEGER').asFloat()).to.equal(parseFloat(TEST_VARS.FLOAT_INTEGER)) }) it('should throw an exception - non float found', function () { From b7ba505a3a8c3f873c2db6e0cfdae2ceb34c7545 Mon Sep 17 00:00:00 2001 From: Dror Weiss <> Date: Sun, 23 Apr 2023 09:46:15 +0300 Subject: [PATCH 2/3] Add another invalid float test --- test/index.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/test/index.js b/test/index.js index 112372a..344ec9e 100644 --- a/test/index.js +++ b/test/index.js @@ -231,6 +231,14 @@ describe('env-var', function () { expect(mod.get('FLOAT_INTEGER').asFloat()).to.equal(parseFloat(TEST_VARS.FLOAT_INTEGER)) }) + it('should throw an exception - non float found', function () { + process.env.FLOAT = '1.o' + + expect(function () { + mod.get('FLOAT').asFloat() + }).to.throw() + }) + it('should throw an exception - non float found', function () { process.env.FLOAT = 'nope' From eb608eca4313a245cda73033f755020c925aacae Mon Sep 17 00:00:00 2001 From: Dror Weiss <> Date: Sun, 23 Apr 2023 10:03:20 +0300 Subject: [PATCH 3/3] Add second isNaN explanation to `asFloat` --- lib/accessors/float.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/accessors/float.js b/lib/accessors/float.js index 80921fd..b61c663 100644 --- a/lib/accessors/float.js +++ b/lib/accessors/float.js @@ -3,6 +3,8 @@ module.exports = function asFloat (value) { const n = parseFloat(value) + // Some values are parsed as valid floats despite being obviously invalid, e.g. "1.o" or "192.168.1.1". + // In these cases we would want to throw an error. if (isNaN(n) || isNaN(value)) { throw new Error('should be a valid float') }