1

I have a receipt that I am working on that does the math for me. I need the results to show up as dollar values.

My HTML:

<input type="text" name="copy1" id="copy1" size="4" maxlength="10" onchange="calculate(this.value)">
<input type="text" name="copycosts" id="copycosts" size="4" VALUE=""/>

My JavaScript:

<script type="text/javascript">
function calculate(){
var copy1value = parseFloat(document.getElementById("copy1").value, 10);
document.getElementById("copycosts").value = copy1value * 0.50;
}
</script>

How do I add 2 decimal places after the multiplication is completed? For instance 13 * 0.50 = 6.5 -- I want it to say 6.50.

Thanks in advance.

mjk
  • 2,443
  • 4
  • 33
  • 33
karisma
  • 49
  • 1
  • 3
  • possible duplicate of [parse float with two decimal places](http://stackoverflow.com/questions/4435170/parse-float-with-two-decimal-places) – i-- Oct 04 '13 at 13:12

3 Answers3

3

Use toFixed() (which will convert the number to a string):

document.getElementById("copycosts").value = (copy1value * 0.50).toFixed(2);

If you need to manipulate this number in future, you'll need to use parseFloat():

var numFromCopycosts = parseFloat(document.getElementById('copycosts').textContent);

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
2

Use below code to also round the number:

(Math.round(copy1value * 0.50 * 100) / 100).toFixed(2);

Example

 1.345 will be rounded off to 1.35

Added jsfiddle: http://jsfiddle.net/FQTqk/297/

Rajesh
  • 3,743
  • 1
  • 24
  • 31
  • 1
    Why are you using `parseFloat()` on a number? But +1 for dealing with the rounding issues raised by `toFixed()`. – David Thomas Oct 04 '13 at 13:15
  • yup. also works without `parseFloat`. Since the user is assigning value into an element, `parseFloat()` is not needed – Rajesh Oct 04 '13 at 13:20
0

You can use toFixed:

var val = copy1Value.toFixed(2);
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176