...

View Full Version : money script



deepforest
09-09-2003, 02:02 PM
Hello
i want to write money script but split with dot.
<input type="text" name="money">

example;
if i write 1000, java script change to 1.000
if i write 100000000, java script change to 100.000.000

(key press)

i can't write it.

please help me
thanks for replies

Danne
09-09-2003, 04:19 PM
Try this:


function toMoney(pNum) {
var num="";
pNum=new String(pNum);
for (var i=pNum.length-1;i>=0;i--) {
num+=pNum.charAt(i);
}
num=num.replace(/(\d{3})/g, "$1.");
pNum="";
for (var i=num.length-1;i>=0;i--) {
pNum+=num.charAt(i);
}
return pNum;
}



document.write( toMoney(1000044000.22) +'<br>' );
document.write( toMoney(90004000) +'<br>' );


The for loops are just to make the regexp read it from the end. I don't know if there's a way to do that in the regexp, which would be to prefer.
It will not work it you use more than two decimals.

Danne
09-09-2003, 07:05 PM
Small adjustment:


function toMoney(pNum) {
var num="";
pNum=new String(pNum);
for (var i=pNum.length-1;i>=0;i--) {
num+=pNum.charAt(i);
}
num=num.replace(/(\d{3})/g, "$1.");
pNum="";
for (var i=num.length-1;i>=0;i--) {
pNum+=num.charAt(i);
}
if (pNum.charAt(0)==".") {
pNum=pNum.slice(1);
}
return pNum;
}



document.write( toMoney(121000044000.22) +'<br>' );
document.write( toMoney(0910004000) +'<br>' );
document.write( toMoney(100) +'<br>' );

cheesebag
09-09-2003, 07:41 PM
Did you say keypress? ;)


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>ugh</title>
<style type="text/css">

input {
width: 100px;
text-align: center;
border: darkgreen solid;
border-width: 1px 2px 1px 2px;
background: buttonface;
}

</style>
<script type="text/javascript" language="javascript">

function $format(oText) {
var v = oText.value.replace(/\./g, ''), i = v.length, j = i - 1, chr, $str = '';
if (/\D/.test(v)) {
alert('Please enter numbers only.');
oText.value = oText.prevValue || '';
return false;
}
while (chr = v.charAt(--i))
$str = (((i - j) % 3 == 0 && (i != j)) ? chr + '.' : chr) + $str;
oText.value = oText.prevValue = $str;
return true;
}

</script>
</head>
<body onload="document.forms[0].elements[0].focus()" style="padding:100px;">
<form>
<input name="t" type="text" onkeyup="return $format(this)" />
<input type="reset" value="clear" style="height:20px;" onclick="t.focus()">
</form>
</body>
</html>

deepforest
09-09-2003, 07:41 PM
it's ok!



thank you very much



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum