Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

javascript - Reliable JS rounding numbers with toFixed(2) of a 3 decimal number

I am simply trying to round up 1.275.toFixed(2) and I was expecting a return of 1.28, rather than 1.27.

Using various calculators and the simple method of rounding to the nearest hundredth, if the last digit is greater than or equal to five, it should round up.

If this doesn't work with toFixed(2), how would it?

People asking whether console.log(1.275.toFixed(2)) prints off 1.28, here's a quick screenshot MacOS Chrome Version 55.0.2883.95 (64-bit)

enter image description here

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The 1.275 base 10 number has finite digits but becomes periodic when converted to base 2:

= 0b1.01000110011001100110011001100110011001100110011010
         ^^^^

Since it has infinite digits, it cannot be represented exactly in a computer unless you use an arbitrary precision library (a library than represents numbers as text to keep them in base 10). JavaScript numbers do not use such library for performance reasons.

Since the original value has already lost precision when it reaches JavaScript, rounding it will not improve that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...