JSFiddle - React, Tailwind, and code Playground
by AntonLapshin
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Coding challenge</title>
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.9.2.css">
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="https://code.jquery.com/qunit/qunit-2.9.2.js"></script>
</body>
</html>
JavaScript
//
// A built-in solution
//
/* const addCommas = input => {
return input.toLocaleString('en', {
maximumSignificantDigits: 21
});
} */
//
// A solution based on Regex. Taken from Internet :)
//
/* const addCommas = input => {
const parts = input.toString().split(".");
return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}
*/
//
// A solution that I've come up with.
// A little bit faster than the regex solution:
// *************************************
// ** https://jsbench.me/62k0rydgrl/5 **
// *************************************
//
const addCommas = input => {
const [head, tail] = input.toString().split('.'),
result = [],
{ length } = head;
let i = 0;
do {
result.push(head.slice(Math.max(length - i * 3 - 3, 0), length - i * 3));
} while(++i < length / 3)
return result.reverse().join(',') + (tail ? ('.' + tail) : '');
}
//
// Another solution that I've come up with.
// The fastest one
// *************************************
// ** https://jsbench.me/62k0rydgrl/5 **
// *************************************
// But it has a flaw: it might add some magic numbers in
// the floating part
// That is caused by the floating point arithmetic issue
// https://floating-point-gui.de/
//
/* const addCommas = input => {
let num = input,
i = 0,
j = 0;
const result = [];
do {
let rem = num % 10;
if (i++ > 0) { // do not round the first remainder of devision
rem = ~~rem;
}
if (j++ === 3) {
result.push(',');
j = 1;
}
result.push(rem);
num /= 10;
} while (num >= 1);
return result.reverse().join('');
} */
[
[0, '0'],
[1, '1'],
[1.555, '1.555'],
[10, '10'],
[1000, '1,000'],
[1000.5, '1,000.5'],
[1901.99, '1,901.99'],
[500, '500'],
[512, '512'],
[5000000, '5,000,000'],
[1901321.990099, '1,901,321.990099']
].forEach(([input, output]) =>
QUnit.test(`${input} => "${output}"`, assert => {
...