Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and write float values from JSON which ends with .0

I have this JSON file:

{
  "weight": 12.0,
  "values": [
    23.4,
    16.5,
    16.8,
    5.0,
    0.0,
    0.0,
    0.0
  ]
}

If I trying to read this file and then write it back (using JSON.parse and JSON.stringify)

const fs = require('fs')

const json = JSON.parse(fs.readFileSync('test.json'))
console.log(json)
fs.writeFile('test2.json', JSON.stringify(json), (error) => {
  if (error) console.log(error) 
})

The output file looks like this:

{
  "weight": 12,
  "values": [
    23.4,
    16.5,
    16.8,
    5,
    0,
    0,
    0
  ]
}

The problem is if float values ends with .0.
But I need keep these values as in the original.

Can I somehow read float value like a string, and then write it like float value
(even if it ends with .0)?

P.S. Node.js v7.7.4

like image 393
DmitryScaletta Avatar asked Dec 11 '25 04:12

DmitryScaletta


1 Answers

For each of them you can use the modulus operator (%) to determine if it's a whole number, and if so convert it to a string and append ".0" to the end of it:

json.values.map(v => {
  return v % 1 === 0 ? v + ".0" : v
})

var json = {
  "weight": 12.0,
  "values": [
    23.4,
    16.5,
    16.8,
    5.0,
    0.0,
    0.0,
    0.0
  ]
}

var result = json.values.map(v => {
 return v % 1 === 0 ? v + ".0" : v
})

console.log(result);
like image 70
James Donnelly Avatar answered Dec 12 '25 18:12

James Donnelly