April 2nd, 2003, 05:41 PM
-
formatted number output with JavaScript
I want to display a number value (such as 1234567) in the form, 1,234,567. How can I do it?
Thanks in advance.
April 3rd, 2003, 03:47 AM
-
Took some effort, but:
Code:
<html>
<head>
<script type='text/javascript'>
function validate() {
text = ""
str = document.forms[0].elements[0].value
for (i = 0; i <= str.length; i++) {
text = str.substring(i, i+1) + text
}
count = 0
for (i = 3; i <= str.length; i = i + 3) {
text = text.substring(0, i + count) + "," + text.substring(i + count,text.length);
count++
}
str = text
text = ""
for (i = 0; i <= str.length; i++) {
text = str.substring(i, i+1) + text
}
document.forms[0].elements[0].value = text
}
</script>
</head>
<body>
<form>
<textarea name='nothing'>
</textarea>
<input type='button' value='validate' onClick='validate()'>
</form>
</body>
</html>
There you have it!
April 3rd, 2003, 08:33 PM
-
<html>
<head>
<title>untitled</title>
<script type="text/javascript">
//// put this anywhere ////
String.prototype.format = function(decplaces) {
var n, i = 0, retStr = '', s = this.split('.');
var rt = null, lt = s[0];
var lgt = lt.length;
if (s.length > 1) rt = s[1].substring(0, (decplaces || s[1].length));
while (n = lt.charAt(i++))
if ((lgt-i) && (lgt-i) % 3 == 0) retStr += n + ',';
else retStr += n;
return retStr + ((rt) ? '.' + rt : '');
}
///////////////////////////
</script>
</head>
<body>
<script type="text/javascript">
var x = '1234567';
document.write(x.format());
document.write('<br />');
x = '3756.4088';
document.write(x.format(2));
document.write('<br />');
x = '905095004877596.22';
document.write(x.format());
</script>
</body>
</html>
April 4th, 2003, 12:36 AM
-