Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get a number without "tail" using charCode

I have the following problem:
when writing a number, I get a big tail. I know it’s related with bits, but how do I avoid this tail? We can’t use native methods and concatenations, parseInt, parseFloat, Number and etc.

function getNum(message) {
  const zero = "0".charCodeAt(0);
  const nine = "9".charCodeAt(0);
  const comma = ",".charCodeAt(0);
  let num = 0,
    factor = 1,
    numStarted = false;

  for (let i = message.length - 1; i >= 0; i--) {
    const charCode = message.charCodeAt(i);

    if (charCode >= zero && charCode <= nine) {
      num = num + (charCode - zero) * factor;
      factor *= 10;
      numStarted = true;
    } else if (numStarted && charCode === comma) {
      num /= factor;
      factor = 1;
    } else {
      numStarted = false;
    }
  }
  return num;
}

console.log(getNum("Today i spend a 56,02 USD, it's a lot for me."));

need result: 56,02.
my result: 56.019999999999996

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It works if you keep the integer and the fractional part separate. Replace

else if (numStarted && charCode === comma) {
  num /= factor;
  factor = 1;
}

with

else if (numStarted && charCode === comma) {
  frac = num / factor;
  num = 0;
  factor = 1;
}

and

return num + frac;

at the end. Also initialize let frac = 0;

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading