John Huang
John Huang

Reputation: 358

Number() fails to convert the string to number in map()

The following comes the code snippet in which there is a two dimensional array from which I want to alter the string value nested at the second level at index 0.

const dataset = [
  ["1947-01-01", 243.1],
  ["1947-04-01", 246.3],
  ["1947-07-01", 250.1],
];
const datasetXY = dataset.map((first) =>
  first.map((second) => {
    if (typeof second == "string") {
      const returnedValue =
        Number(second.substring(0, 4)) +
        (Number(second.substring(5, 7)) / 12).toFixed(2);
      return returnedValue;
    } else {
      return second;
    }
  })
);

The returned array should be like the following:(whether it's rounded to the second decimal place doesn't matter that much). However, the returned values at the second level at index 0 are still "string" rather than number. Is there anything I mess up above?

  [
    [
      1947.01,
      243.1
    ],
    [
      1947.34,
      246.3
    ],
    [
      1947.58,
      250.1
    ]
  ]

Upvotes: 1

Views: 454

Answers (2)

Jeremy Thille
Jeremy Thille

Reputation: 26390

Surprisingly, .toFixed() returns a string! This converts your whole number back to a string.

the fix is easy : just return +returnedValue (quick conversion, similar to Number(returnedValue))

const dataset = [
  [
    "1947-01-01",
    243.1
  ],
  [
    "1947-04-01",
    246.3
  ],
  [
    "1947-07-01",
    250.1
  ]
]
const datasetXY = dataset.map(first => first.map(second => {
  if (typeof second == "string") {
    const returnedValue =
      Number(second.substring(0, 4)) +
      (Number(second.substring(5, 7)) / 12).toFixed(2)
    return +returnedValue
  } else {
    return second
  }
}))

console.log(datasetXY)

This is the kind of bug that Typescript easily prevents. By typing your function (first.map( (second:string|number):number => {...), Typescript would tell you "Your function is expected to return a number, but it's returning a string".

Upvotes: 4

Pranjal Nanavaty
Pranjal Nanavaty

Reputation: 135

toFixed() returns a string. You can explicitly convert the value returned by toFixed() to type number.

const dataset = [
  ["1947-01-01", 243.1],
  ["1947-04-01", 246.3],
  ["1947-07-01", 250.1],
];
const datasetXY = dataset.map((first) =>
  first.map((second) => {
    if (typeof second == "string") {
      const returnedValue =
        Number(second.substring(0, 4)) +
        Number((Number(second.substring(5, 7)) / 12).toFixed(2)); // explicitly convert value returned by .toFixed() to number
      return returnedValue;
    } else {
      return second;
    }
  })
);

Upvotes: 1

Related Questions