Format numbers with grouped thousands
JavaScript performance comparison
Info
Dmitry Baranovskiy blew my mind with his dirtyCommas function, in which a very clever regular expression is used to format numbers with grouped thousands. Let’s see how it compares to other solutions.
Note that the functions benchmarked here were designed for use with positive integers only.
Preparation code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
function formatNumber1(number) {
var comma = ',',
string = Math.max(0, number).toFixed(0),
length = string.length,
end = /^\d{4,}$/.test(string) ? length % 3 : 0;
return (end ? string.slice(0, end) + comma : '') + string.slice(end).replace(/(\d{3})(?=\d)/g, '$1' + comma);
}
function formatNumber2(number) {
return Math.max(0, number).toFixed(0).replace(/(?=(?:\d{3})+$)(?!^)/g, ',');
}
</script>
Preparation code output
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
100 |
|
pending… |
Dmitry’s clever regex |
|
pending… |
Compare results of other browsers
Revisions
You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:
- Revision 1: published by Mathias Bynens
- Revision 2: published
1 comment
It doesnt work with numbers higher than 99,999,999