Get a number from a string using charCodeAt

123 views Asked by At

Need to get a number using only one loop for and charCodeAt() We can't use native methods and concatenations, parseInt, parseFloat, Number, +str, 1 * str, 1 / str, 0 + str, etcc

const text = "In this market, I lost 0,0000695 USDT, today is not my day";

function getAmount(str) {
  const zero = "0".charCodeAt(0);
  const nine = "9".charCodeAt(0);
  const coma = ",".charCodeAt(0);
  let num = 0,
    factor = 1;

  for (let i = str.length - 1; i >= 0; i--) {
    const char = str.charCodeAt(i);
    if (char >= zero && char <= nine) {
      num += (char - 48) * factor;
      factor *= 10;
    }
  }
  return num;
};

console.log(getAmount(text));

Need result: 0,0000695 My current result is 695

Tell me how to correct the formula for writing zeros

1

There are 1 answers

1
001 On BEST ANSWER

When you hit a comma, you need to convert the current value to a fraction:

const getAmount = (str) => {
    const zero = "0".charCodeAt(0);
    const nine = "9".charCodeAt(0);
    const comma = ",".charCodeAt(0);
    let num = NaN, // Init to NaN as a sentinal value. Could also use null.
        factor = 1;      
    let haveComma = false;

    for (let i = str.length - 1; i >= 0; i--) {
        const char = str.charCodeAt(i);
        // Break when: it's not a number and not a comma, but we have parsed number
        const isParsable = (char == comma && !haveComma) || !isNaN(str.charAt(i));
        if (!isParsable && !isNaN(num)) break;
        else if (char >= zero && char <= nine) {
            if (isNaN(num)) num = 0; // Reset from NaN to Zero, first time only
            num += (char - 48) * factor;
            factor *= 10;
        }
        // On comma, convert num to a fraction and reset factor
        // Ex: num = 123 -> num = .123
        else if (char == comma && !isNaN(num)) {
            num /= factor;
            factor = 1;
            haveComma = true;
        }
    }
    return num;
}

const text = "In this market I lost $10,0000695 USDT, today is not my day";
console.log(getAmount(text));


I just noticed that my answer is similar to a previously deleted answer. The issue with that answer is that they did not handle multiple commas in the string.