Rach
Rach

Reputation: 1

3 decimal places in javascript

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

Answers (3)

user2289659
user2289659

Reputation:

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

Upvotes: 1

sumon
sumon

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

Chris Dixon
Chris Dixon

Reputation: 9167

Have you tried:

document.writeln (a + " / " + b + " = " + (a/b).toFixed(3) + "<br />")

Upvotes: 3

Related Questions