• 973
• 1.7k
• 297.6k

# javascript function takes numeral with digits instead of seperators?

Mar 23 2023 6:25 PM

Hi Team

I need help with below instruction of this function;

// instruction

Create a function that takes a numeral (just digits without separators (e.g. 19093 instead of 19,093) and returns the standard way of reading a number, complete with punctuation.

``````sayNumber(0) ? "Zero."

sayNumber(11) ? "Eleven."

sayNumber(1043283) ? "One million, forty three thousand, two hundred and eighty three."

sayNumber(90376000010012) ? "Ninety trillion, three hundred and seventy six billion, ten thousand and twelve."``````

Notes

Must read any number from 0 to 999,999,999,999,999.

// My code does not pass all test and failed.

``````function sayNumber(num) {
return BigInt(num).toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}

function test(num, expect) {
const result = sayNumber(num);
const pass = result === expect;
console.log(`\${pass ? "?" : "ERROR ====>"} \${num} => \${result}`);
return pass;
}

let failures = 0;
failures += !test(0, "0");
failures += !test(100, "100");
failures += !test(1000, "1,000");
failures += !test(10000, "10,000");
failures += !test(100000, "100,000");
failures += !test(1000000, "1,000,000");
failures += !test(10000000, "10,000,000");
failures += !test(999999999999999n, "999,999,999,999,999");
if (failures) {
console.log(`\${failures} test(s) failed`);
} else {
console.log("All tests passed");
}``````

// Errors it compiles

``````? 0 => 0
? 100 => 100
? 1000 => 1,000
? 10000 => 10,000
? 100000 => 100,000
? 1000000 => 1,000,000
? 10000000 => 10,000,000
? 999999999999999 => 999,999,999,999,999
All tests passed
FAILED: Expected: 'Zero.', instead got: '0'
FAILED: Expected: 'Eleven.', instead got: '11'
FAILED: Expected: 'Fourteen.', instead got: '14'
FAILED: Expected: 'Fifteen.', instead got: '15'
FAILED: Expected: 'Forty-three.', instead got: '43'
FAILED: Expected: 'Fifty.', instead got: '50'
FAILED: Expected: 'One thousand and one.', instead got: '1,001'
FAILED: Expected: 'Twenty thousand.', instead got: '20,000'
FAILED: Expected: 'One million, thirty-three thousand, two hundred and eighty-six.', instead got: '1,033,286'
FAILED: Expected: 'Twelve million and thirteen.', instead got: '12,000,013'
FAILED: Expected: 'Ninety trillion, three hundred and seventy-six billion, ten thousand and twelve.', instead got: '90,376,000,010,012'``````