Skip to content Skip to sidebar Skip to footer

Not Able To Convert String To Float

I have a simple array of string but I am trying to convert it to array of decimal numbers like [5.22,8.22,rest of the numbers], but it is returning only array of whole numbers. I

Solution 1:

Change acc.push(parseFloat(crr)) to acc.push(parseFloat(crr.replace(":",".")))

JavaScript doesn't recognize colons as periods


Solution 2:

A float number doesn't follow this format integer:decimal,

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

On the other hand, you don't need reduce for doing that, use the function map instead.

Likewise, I recommend you to use the object Number. If you want, you can read a little about it 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; }

Post a Comment for "Not Able To Convert String To Float"