-1

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?

Sunil Kumar Das
  • 372
  • 1
  • 2
  • 12
Ilir
  • 488
  • 5
  • 20
  • 3
    Just keep the initial value around? There isn't a "number, which also includes text but is still a number, even though there is a string somehow attached to it". – VLAZ Feb 01 '23 at 13:16
  • If you already have the string then you already have it. const orig = "100 MB", const numberPart = parseFloat(orig) – terpinmd Feb 01 '23 at 13:35
  • Just to be more precise. The data is a table and each table cell has some values ("100 MB", "2 GB", "6 TB"...) so i need to convert them to numbers in order to apply filters to the table. But then i need to use the same values in the filter items but they need to be strings just as the initial value. However the below answer is a good workaround. – Ilir Feb 01 '23 at 13:42
  • `const originalCellContent = cell.getContentInAppropriateWay()`. Use the original value later. You don't have to reconstruct it (which risks the reconstructed value not matching the original representation). – VLAZ Feb 01 '23 at 13:50
  • It goes to filter before it gets rendered in the table cell. Anyway, i thought maybe theres some workaround other than `parseFloat()` to make me achieve what i need. Thanks. – Ilir Feb 01 '23 at 14:03

1 Answers1

1

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);
Ghassan Elias
  • 2,213
  • 1
  • 14
  • 17