Skip to content

Commit

Permalink
Fix 1.0 not recognized as float (#166)
Browse files Browse the repository at this point in the history
* Fix 1.0 not recognized as float

* Add another invalid float test

* Add second isNaN explanation to `asFloat`

---------

Co-authored-by: Dror Weiss <>
  • Loading branch information
dror-weiss authored Apr 24, 2023
1 parent 7a47152 commit 7629cd9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/accessors/float.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
module.exports = function asFloat (value) {
const n = parseFloat(value)

if (isNaN(n) || n.toString() !== 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')
}

Expand Down
10 changes: 10 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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"}',
Expand Down Expand Up @@ -227,6 +228,15 @@ 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 () {
process.env.FLOAT = '1.o'

expect(function () {
mod.get('FLOAT').asFloat()
}).to.throw()
})

it('should throw an exception - non float found', function () {
Expand Down

0 comments on commit 7629cd9

Please sign in to comment.