...

View Full Version : Changing decimal separater and having 2 decimal places



xenix
09-27-2012, 07:48 PM
Hi, Im working on a Order form for a friend in Germany (which is more challenging than I had hoped for)

So the problem:
I have set up everything so far that when a new item is selected the price (total) is also changed, My problem and question is how can I convert the decimal separater(from a dot to a comma as well as have 2 decimal places (eg 10.50 needs to be 10,50)), as everytime i try to add a .toFixed(2); it breaks the javascript. Im currently trying to go from one field that shows the total that and then one that shows the total with comma and decimal place...

Trust me I have searched, ive tryed many differnt things but I just cant get it to work :(

Heres the code behind the form


<script language="JavaScript">
function calculateRadio(){

var op1=document.getElementsByName('form[senfe][]');
var op2=document.getElementsByName('form[oel][]');
var result=document.getElementById('Total');

result.value=0;
result.value=parseInt(result.value);
for(i=0;i<op1.length;i++)
if(op1[i].checked) result.value=parseFloat(result.value)+parseFloat(op1[i].value);
for(i=0;i<op2.length;i++)
if(op2[i].checked) result.value=parseFloat(result.value)+parseFloat(op2[i].value);

addComma();
}

function addComma(){

var str=Total.value;
var n=str.replace(/\./g, ",");
comma.value=n;}

</script>

And a link to the form http://idee-genuss.de/index.php?option=com_rsform&formId=13

Its not pretty, wanted to get it working before I spent to much time on it.

:o

xelawho
09-27-2012, 08:07 PM
it's unwise to refer to elements by their bare ID (although you can get away with it in most browsers). For toFixed() to work, you need to start off with a number. An input's value will always be a string...



var str=Number(document.getElementById('Total').value);
var num=str.toFixed(2).replace(/\./g, ",")
alert(num)


or if you wanted to keep it all on one line for some reason:


var num=Number(document.getElementById('Total').value).toFixed(2).replace(/\./g, ",");
alert(num)

Philip M
09-27-2012, 08:49 PM
var str=Number(document.getElementById('Total').value);
var num=str.toFixed(2).replace(/\./g, ",")
alert(num)



More logical to name the variables


var num=Number(document.getElementById('Total').value); //a number
var str=num.toFixed(2).replace(/\./g, ","); // now a string
alert(str);

<script language=javascript> is long deprecated. Use <script type = "text/javascript"> instead (in fact also deprecated but still necessary for IE<9).

xenix
09-27-2012, 08:59 PM
Thank you so much, you saved me from pulling out the last hair on my head :)

:o



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum