0

I want a simple calculation form. I took te example of w3schools:

and this is myd adjusted code:

<!DOCTYPE html>
<html>
<body>

<form oninput="x.value=parseFloat(a.value).round(2)* parseFloat(b.value).round(2)">
<input type="number" id="a" value="50">
+<input type="number" id="b" value="50">
=<output name="x" for="a b"></output>
</form>

<p><strong>Note:</strong> The output tag is not supported in Internet Explorer.</p>

</body>
</html>

when I add the round(2) (form oninput)then it won't work. if I remove it, it wil work. But if I add some numbers after the decimal, the I get a whole bunch of numbers with lots of zerro's.

I just want a 2 digit output.

can anyone help me please?

I also checkout this link:

parse float with two decimal places

but I can't get it to work

Community
  • 1
  • 1
Ralph Schipper
  • 701
  • 2
  • 12
  • 24

1 Answers1

2

Let's say you're multiplying 0.11 and 0.12 - both numbers with two decimal places. The result is 0.132, which has three. And that's assuming you're using numbers that can be represented accurately: most decimal numbers can't.

Rather than rounding the inputs, you should round the output:

x.value = (a.value*b.value).round(2);

That being said, I don't think round is a function to be used like that. I think you need to do this:

x.value = Math.round(a.value*b.value*100)/100;

Note that because * automatically casts its arguments to numbers (unlike +), there is no need to explicitly parseFloat.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592