简体   繁体   中英

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
    ]
  ]

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".

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;
    }
  })
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM