无法将字符串转换为浮点数

时间:2018-10-20 14:53:53

标签: javascript

我有一个简单的字符串数组,但是我试图将其转换为十进制数字数组,例如[5.22,8.22,其余数字],但是它只返回整数数组。

我正在犯一些我无法注意到的菜鸟错误

let k = ["5:17", "8:22", "3:34", "5:23",
         "7:12", "7:24", "6:46", "4:45",
         "4:40", "7:58", "11:51", "9:13",
         "5:50", "5:52", "5:49", "8:57",
         "11:29", "3:07", "5:59", "3:31"];

let arrOfNum = k.reduce(function(acc, crr) {
  acc.push(parseFloat(crr))
  return acc;
}, [])

console.log(arrOfNum)

2 个答案:

答案 0 :(得分:4)

acc.push(parseFloat(crr))更改为acc.push(parseFloat(crr.replace(":",".")))

JavaScript无法将冒号识别为句点

答案 1 :(得分:1)

浮点数不遵循此格式integer:decimal

it follows `integer.decimal`
                   ^
                   |
                   +--- the dot is the decimal separator in JS.

另一方面,您不需要reduce,而可以使用函数map

同样,我建议您使用对象Number。如果您愿意,可以阅读一些here

let k = ["5:17", "8:22", "3:34", "5:23","7:12", "7:24", "6:46", "4:45","4:40", "7:58", "11:51", "9:13","5:50", "5:52", "5:49", "8:57","11:29", "3:07", "5:59", "3:31"],
    arrOfNum = k.map((crr) => Number(crr.replace(':', '.')));

console.log(arrOfNum);
.as-console-wrapper { max-height: 100% !important; top: 0; }