0

I'm new to programming and I am starting with javascritpt, I have this code and I want the printed values to be to 3 decimal places.

<script>
for (var a = 3, b = 2; b >= 0; a ++, b --) {
document.writeln (a + " / " + b + " = " + a/b + "<br />")
}
</script>

I tried:

var a=a.toFixed(3);
var b=b.toFixed(3); 

but it doesn't make a difference. The fist line comes out as 4 / 3 = 1.3333333333333333 instead of 1.333 which is what I want.

Rach
  • 1
  • 1
  • 1
    Possible duplicate of [Formatting a number with exactly two decimals in JavaScript](http://stackoverflow.com/questions/1726630/formatting-a-number-with-exactly-two-decimals-in-javascript) – devRicher Jan 02 '17 at 22:02

3 Answers3

3

Have you tried:

document.writeln (a + " / " + b + " = " + (a/b).toFixed(3) + "<br />")
Chris Dixon
  • 9,147
  • 5
  • 36
  • 68
1

You can use .toFixed(3) at the time you divide. Like (a/b).toFixed(3)

0

Try this:

<script>
for (var a = 3, b = 2; b >= 0; a ++, b --) {
    var c = (a/b).toFixed(3);
    document.writeln (a + " / " + b + " = " + c + "<br />")
}
</script>
sumon
  • 742
  • 1
  • 11
  • 33