JavaScript-Number的各種地雷--浮點數運算

莊創偉
1 min readDec 12, 2017

JS在浮點數運算上會有精度的問題

主要是因為JS運算是依循IEEE754的規範,在運算時會轉換成2進制,而浮點數在轉成二進制時會造成無窮迴圈,進而產生運算誤差

0.1+0.2 !=0.3

JS有對此有.toFixed語法來處理浮點數問題

(0.21+0.32).toFixed(10) ==>0.5

.toFixed(x) ,x為精度範圍,需為0~20 ,超出精度範圍的部分會以四捨五入方式處理(同樣遵循IEEE754,所以在負數的四捨五入會成為四捨六入)

網路上也有許多套件可以處理複雜運算與浮點數運算的問題,如 :math.jsNumera.js

但是.toFixed在較早期的瀏覽器中不支援,故也可自行處理浮點數運數。一般是先將其轉成整數後進行運算,再補回小數點

*整數在超過1e後也會有運算精度上與溢位的問題

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

莊創偉
莊創偉

Written by 莊創偉

學海無涯。但是為了生計還是得下海的風塵男子

No responses yet

Write a response