0

Forgive me for the stupid question but I'm a JS noob.

I created this the following code but can't get to round it (2 decimals).

Please help!

<html>  
<head>  
<title>Simple Calc</title>  
<script language="javascript" type="text/javascript">  
function combineder(){  
a=Number(document.calculator.number1.value);  
b=Number(document.calculator.number2.value);
c=(a/452)/(b/100)
document.calculator.total.value=c;  
}  
</script>  
</head>  
<body>  
<form name="calculator">  
A: <input type="text" size="2"name="number1">   
<BR>  
B: <input type="text" name="number2">   
<BR>
<input type="button" value="Calculate!" onclick="javascript:combineder();">  
<br>
Your results is: $<input type="text" name="total">   

</form>  

</body>  
</html>
iddo
  • 551
  • 1
  • 4
  • 5

4 Answers4

1

Firstly, you should not use javascript:etc... in an onclick attribute, I think you are getting mixed up with the href attribute executing javascript as a url. Instead, you should simply have onclick="combineder();"

Secondly, you should use var to declare variables in the local scope, so they do not collide with other variables in the global namespace. Declare variables like this: var c = 123;

For your question, you can do this to round to 2 dp - which will not leave trailing 0s

// ...
var c=(a/452)/(b/100)
c = Math.round(c*100)/100
// ...

Or this, which will always leave trailing 0s and will be returned as a string representation of the number

// ...
var c=(a/452)/(b/100)
c = c.toFixed(2)
// ...

Related answer: https://stackoverflow.com/a/7343013/665261

Community
  • 1
  • 1
Billy Moon
  • 57,113
  • 24
  • 136
  • 237
0

Try using .toFixed(). Here's an example

var myNum = 10.45621;
var newNum = myNum.toFixed(2);

Just pass the number of decimal places you wish to round to into the .toFixed() method. Please check here for more info in the toFixed() method.

Mark Walters
  • 12,060
  • 6
  • 33
  • 48
0

JavaScript has number.toFixed( [digits] )

You want two places so it would be

document.calculator.total.value=c.toFixed(2); 
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

Just use

.toFixed(2);

to cut it to 2 decimals

or you can use

Math.round();

to round it.

Cristiano Fontes
  • 4,920
  • 6
  • 43
  • 76