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 = "Hello team, I checked my wallet balance, there is 0,0000341 USDT, I can not buy anything";
const parseBalance = (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(parseBalance(text));
Need result: 0.0000341
My current result is 341
Tell me how to correct the formula for writing zeros
2
Answers
I would process from left to right and modify the factor by 0.1 for every number you find. You will also need to deal with the float precision issues in Javascript, so before returning the final number call the precisionRound function. This function will round to the appropriate precision according to how many numbers were processed.
When you hit a comma, you need to convert the current value to a fraction:
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.