Skip to content

Instantly share code, notes, and snippets.

@yckart
Forked from 140bytes/LICENSE.txt
Last active December 21, 2015 23:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yckart/6383947 to your computer and use it in GitHub Desktop.
Save yckart/6383947 to your computer and use it in GitHub Desktop.
formatNumber
function (
a, // a number
b, // decimal seperator (optional)
c, // thousands seperator (optional)
d, // decimals (optional)
e, // parts-placeholder
f // decimal-placeholder
) {
e = (a-0).toFixed(d||2).split('.'); // parse to a fixed float and split
return e[0].replace(/(\d)(?=(?:\d{3})+$)/, '$1' + (c || ',')) // get thounds and add its seperator
+ ((f = e[1]) ? (b || '.') + f : ''); // get all decimals and add its seperator
};
function(a,b,c,d,e,f){e=(a-0).toFixed(d||2).split('.');return e[0].replace(/(\d)(?=(?:\d{3})+$)/,'$1'+(c||','))+((f=e[1])?(b||'.')+f:'')}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2013 Yannick Albert <http://yckart.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "formatNumber",
"description": "Formats a number to look like currency, percentages, times, or even plain old numbers with decimal places, thousands, and abbreviations.",
"keywords": [
"format",
"number",
"currency",
"money",
"decimal"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>undefined</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var formatNumber = function(a,b,c,d,e,f){e=(a-0).toFixed(d||2).split('.');return e[0].replace(/(\d)(?=(?:\d{3})+$)/,'$1'+(c||','))+((f=e[1])?(b||'.')+f:'')};
var tests = {
1: '1.00',
12: '12.00',
123: '123.00',
1234: '1,234.00',
12345: '12,345.00',
123456: '123,456.00',
1234567: '1,234567.00',
12345678: '12,345678.00',
123456789: '123,456789.00',
1234567890: '1,234567890.00'
};
for (var n in tests)
document.getElementById('ret').innerHTML += '<li>' + formatNumber(n) + '</li>';
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment