Home > front end >  JavaScript: turn a string into a number and then turn it back to string
JavaScript: turn a string into a number and then turn it back to string

Time:02-01

I'm receiving some data which I need to turn them to numbers, make some computation with that and then I need to use the same data in another place but as a string. I'm using parseFloat() but the problem is that it already removes the letters part of that number.

    const string = parseFloat("100 MB")
    console.log(string) // 100

Is there something else other than parseFloat() to turn a string into a number but somehow keep the MB part of the string if I want to turn it back as the original string?

CodePudding user response:

const string = "100 MB";

let toArr = string.split(' ');
// do your math computation
let num = parseFloat(toArr[0]) * 10.25   1.14; // whatever
let result = ''.concat(num, ' ', toArr[1]);
console.log(result);

  • Related