Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm new to JavaScript and just discovered toFixed() and toPrecision() to round numbers. However, I can't figure out what the difference between the two is.

What is the difference between number.toFixed() and number.toPrecision()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
306 views
Welcome To Ask or Share your Answers For Others

1 Answer

toFixed(n) provides n length after the decimal point; toPrecision(x) provides x total length.

Ref at w3schools: toFixed and toPrecision

EDIT:
I learned a while back that w3schools isn't exactly the best source, but I forgot about this answer until I saw kzh's, uh, "enthusiastic" comment. Here are additional refs from Mozilla Doc Center for toFixed() and for toPrecision(). Fortunately for all of us, MDC and w3schools agree with each other in this case.

For completeness, I should mention that toFixed() is equivalent to toFixed(0) and toPrecision() just returns the original number with no formatting.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...