...

View Full Version : How do I fix this?



computerguy
06-26-2012, 03:54 AM
Can some one please help me with my java script?
My java script consistently counts up, the problem is the cents character length is way too long (need 2 characters max). Another problem is, I don't know what code additionally I need to put commas in the correct position for determining the proper amount. Example: 12345.67 vs 12,345.67. If some one can just take a look at the code, modify it and re-post the full code since I have no idea what to do, I would deeply appreciate it. :confused:

http://jsfiddle.net/pqsH6/

Old Pedant
06-26-2012, 04:56 AM
Next time, just post the code here instead of in some other place.

Your code is both overkill and underkill.



<html>
<head>
<style type="text/css">
#counter {
margin:0px 0px 0px 0px;
float: left;
}
#ds {
margin:0px 0px 0px 7px;
float: left;
font-weight: bold;
}
</style>
</head>
<body>
<p style="float:left;">Money Saved: </p>
<p id="ds">$</p><div id="counter"></div>
<script type="text/javascript">
var START_DATE = new Date(2012,0,1,12,0,0); // january 1, 2012 12:00:00

var INTERVAL = 1000; // savings per second
var INCREMENT = 0.005; // money saved per second
var START_VALUE = -50000; // configures proper savings calculation

function tick( )
{

var now = new Date();
var count = parseInt((now.getTime() - START_DATE.getTime())/msInterval)
* INCREMENT + START_VALUE;
var pretty = count.toFixed(2);
if ( pretty.length > 6 )
{
pretty = pretty.substring(0,pretty.length-6) + "," + pretty.substring(pretty.length-6);
}
document.getElementById('counter').innerHTML = pretty;
}
tick();
setInterval( tick, INTERVAL );
</script>
</body>
</html>

Philip M
06-26-2012, 08:46 AM
Small error - should be

var count = parseInt((now.getTime() - START_DATE.getTime())/INTERVAL) * INCREMENT + START_VALUE;

Old Pedant's code will only insert commas up to $999,999.99. If you need bigger than that:-




<script type="text/javascript">

// works with negative numbers also
function formatNumber(x) {
return x.toFixed(2).split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'');
}

var num = formatNumber(1234567.8897);
num = "$" + num;
alert (num);

</script>

or add to Old Pedant's code to extend to 999999999.99


if ( pretty.length > 10 ) {
pretty = pretty.substring(0,pretty.length-10) + "," + pretty.substring(pretty.length-10);
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum