Feedback on: irt.org FAQ Knowledge Base Q8
Worth:
Very worth reading
Comments:
Both functions fail for input with decimal places.
Here is my version:
function thousands(str) if (decipos>=0) } Worth: Comments: Thanks for the help. Worth: Comments: <script language="JavaScript1.1"></script> Worth: Length: Technical: Comments: Worth: Length: Technical: Comments:
{
var saveStr = "" + str;
var decipos=saveStr.indexOf('.');
var deciStr="";
if (decipos>=0)
{
deciStr+=saveStr.substring(decipos,100);
saveStr=saveStr.substring(0,decipos);
}
if (saveStr.length < 4) return str;
var revStr = reverseIt(saveStr);
var newStr = '';
for (var i=0;i
if (i>0 && (i%3)==0) newStr += ',';
newStr += revStr.charAt(i);
}
newStr=reverseIt(newStr);
{
newStr+=deciStr;
}
return(newStr);
Very worth reading
I used Val Todorov's method but had to add a test for negative number, reverse sign of number then put sign in front of join as: var sign = "";
if (n<0){sign = "-";n = n*(-1)}
then return sign+arr.join();.
Very worth reading
It doesn't look like these can handle negative numbers. Here is a version based on Val Todorov's, which handles negative numbers as well as decimals.
<form>
<input type="text" name="input">
<input type="text" name="output">
<input type="button"
onClick="this.form.output.value=number_comma_format(this.form.input.value)" VALUE="Number Format">
</form>
Not worth reading
A slightly complicated version:
var n = 12345678.91011;
function commas(n){
var d = (''+n).split('.'), x=(d[0].length+2)%3;
d[0] = ('00'.slice(x)+d[0]).match(/\d{3}/g).join(',').slice(2-x);
return d.join('.');
}
Very worth reading
Just right
Just right
This solution also works with decimals and negatives.
<script type="text/javascript">
function format(number)
{
var text = new String(number);
var negative = text.charAt(0) == '-';
while(true)
{
var i = text.indexOf(",");
if(i == -1)
i = text.indexOf(".");
if(i == -1)
i = text.length;
if(i > 3 && !negative || i > 4)
text = text.substring(0,i-3)+","+text.substring(i-3);
else
return text;
}
}
document.write(format(-123456789) + "<br/>");
document.write(format(1233456.13) + "<br/>");
</script>