Reputation: 1
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.
Upvotes: 0
Views: 302
Reputation:
You can use .toFixed(3)
at the time you divide. Like (a/b).toFixed(3)
Upvotes: 1
Reputation: 742
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>
Upvotes: 0
Reputation: 9167
Have you tried:
document.writeln (a + " / " + b + " = " + (a/b).toFixed(3) + "<br />")
Upvotes: 3