Click to See Complete Forum and Search --> : format a number


CMG
02-28-2003, 01:57 PM
Hi,

I'm exploring java and want to try some things. I'm stuck with the following problem:
I'm picking up formvalues to a function which calculates numbers, currency that is and (wich I was born in the USA) it happens to be Euro's with a comma as decimal separator.
The values from two field have to be summarized with a maximum of 2 numbers after the comma.
I'm using this function:

function newtotal()
{document.TELFORM.TOTAL.value=
parseInt(document.TELFORM.PR_BE.value,10)+
parseInt(document.TELFORM.PR_MO.value,10)}

When I fill the fields in my form with numbers like
11,23 and 22,07 I get 33 as a result.

Furthermore I noticed that when I put a in value greater than 1000,00 (looks like 1.007,45 the sum becomes 1 of the total field.

Can somebody give me a hand?

Phil Karras
02-28-2003, 02:45 PM
Wonderful question! This was asked on a board I help out with over a year ago, unfortuantely there is no easy way to do thiws in JS. You must create a complete function to do what you want done.

If the value is a number ir drops trailing 0's and the decimal point if there is nothing after it.

I wrote a function to do this in the US, you simply need to modify it to use a comma insread.

// -------------------------------------------------------------------
// Converts a numeric to a money string
// Input: a numeric that's supposed to me money, 2 decimal places
// Return: A Money numeric-string, rounded & truncated to 2 places
// -------------------------------------------------------------------
function Money(amount) {
var a = amount * 100;
a = Math.ceil(a);
a /= 100;
var b = parseInt(a);
if (a == b) { // If it IS an int then add the decimal point
a += ".";
}
a += "00"; // converts it to a string with exta 0's
var where = a.indexOf(".");
var b = a.substring(0, where+3);
return(b); // returns a STRING in money format
}

Dan Drillich
02-28-2003, 02:50 PM
The following script can put you in the right direction -


var x = "1,1";
var y = "2,2";

x = x.replace(/,/,".");
y = y.replace(/,/,".");
alert(x);
alert(y);

x = parseFloat(x);
y = parseFloat(y);

var s = x+y;
s = s.toFixed(2);

alert(s);

Dan Drillich
02-28-2003, 03:55 PM
Try this -


<script type="text/javascript">

function newtotal() {

var x = document.TELFORM.PR_BE.value;
var y = document.TELFORM.PR_MO.value;

x = x.replace(/,/,".");
y = y.replace(/,/,".");

x = parseFloat(x);
y = parseFloat(y);

var s = x+y;
s = s.toFixed(2);

document.TELFORM.total.value = s;
}

// -->
</script>

<form name="TELFORM" onsubmit="newtotal(); return false;">

<input type="text" name="PR_BE">
+
<input type="text" name="PR_MO">
=
<input type="text" name="total">
<input type="submit">


</form>