Skip to content

Commit

Permalink
Fix float parsing causing conversion data loss (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
extremeheat committed Aug 21, 2023
1 parent a41a0ce commit 66b155d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
7 changes: 6 additions & 1 deletion index.js
Expand Up @@ -48,7 +48,12 @@ function fromCSV ({ data, file, separator = ',', headerFields, overrideExistingH
const row = split(line, separator)
const obj = {}
for (const i in headers) {
obj[headers[i]] = (parseFloats && !isNaN(row[i])) ? parseFloat(row[i]) : row[i]
let val = row[i]
if (parseFloats && !isNaN(val)) {
const floatVal = parseFloat(val)
if (floatVal.toString() === row[i]) val = floatVal
}
obj[headers[i]] = val
}
out.push(obj)
}
Expand Down
8 changes: 8 additions & 0 deletions test/basic.test.js
Expand Up @@ -46,6 +46,14 @@ describe('basic', () => {
assert.deepStrictEqual(json, [{ a: 'hello', b: 'world', c: 3.14159 }])
})

it('NOT parses bad floats', () => {
const json = dumbcsv
.fromCSV({ data: '436E0248,3.141592653589793238462643383279502884197,3.14159', headerFields: ['a', 'b', 'c'] })
.toJSON()
console.log(json)
assert.deepStrictEqual(json, [{ a: '436E0248', b: '3.141592653589793238462643383279502884197', c: 3.14159 }])
})

it('NOT parses floats', () => {
const json = dumbcsv
.fromCSV({ data: 'hello,world,3.14159', headerFields: ['a', 'b', 'c'], parseFloats: false })
Expand Down

0 comments on commit 66b155d

Please sign in to comment.