PDA

View Full Version : 2 decimals and adding , for 1,000+


badmix
07-13-2002, 04:29 AM
i'm stuck trying to have all numbers shown with only 2 decimals and adding the , for numbers 1,000 plus. how can i do this?

<SCRIPT LANGUAGE="JavaScript">
<!--
function roundoff(amount) {
return (amount == Math.floor(amount)) ? amount + '.00' : ( (amount*10 == Math.floor(amount*10)) ? amount + '0' : amount);
}


function total(what,number) {
var grandTotal = 0;
var yearTotal = 0;
for (var i=0;i<number;i++) {
if (what.elements['price' + i].value == '')
what.elements['price' + i].value = '0.00'; // fix for Opera.

what.elements['subtotal' + i].value=(what.elements['quantity' + i].value - 0) * (what.elements['price' + i].value - 0);
if (what.elements['quantity' + i].value == "0")
what.elements['subtotal' + i].value = "0.00";

subtotal=what.elements['subtotal' + i].value
grandTotal += (what.elements['price' + i].value - 0) * (what.elements['quantity' + i].value - 0);
}

subtotal=roundoff(Math.round(subtotal*Math.pow(10,2))/Math.pow(10,2));
what.grandTotal.value = roundoff(Math.round(grandTotal*Math.pow(10,2))/Math.pow(10,2));

what.elements['yearTotal'].value=(what.elements['grandTotal'].value - 0) * (12);

}
//-->
</SCRIPT>

Soldier Bob
07-13-2002, 05:30 AM
The only way I know is to manually parse the numbers yourself...

:\

-S. Bob

jkd
07-13-2002, 06:09 AM
Number.prototype.prettyPrint = function() {
return this.toFixed(2).split('').reverse().join('').replace(/(\d{3}(?=\d))/g,'$1,').split('').reverse().join('');
}

Works in IE5.5+ and NS6 at least. :)

Heh, gotta love the one-liners I pull outta nowhere with some crafty RegExp work. :D

BTW, to use it:


3547654.5966.prettyPrint() == "3,547,654.60"

badmix
07-13-2002, 07:15 PM
http://www.jsmadeeasy.com/javascripts/Forms/Currency%20Format/index.htm

is there ANY way to add this so it does it automatically with what is entered on my form (without entering a number and clicking the convert button)???

nolachrymose
07-13-2002, 07:41 PM
Use the onblur event handler of the input element.

Hope that helps!

Happy coding! :)

badmix
07-13-2002, 07:45 PM
i've been pulling my hair out trying to get this to work - can anyone tell me what i need to put and where (talk to me like i'm 4!!)???

jkd
07-13-2002, 08:16 PM
onblur="this.value = parseFloat(this.value).prettyPrint()"

In an <input type="text"/> should do the trick. :)