Javascript的數學難題
首先先考大家幾個數學題,如果這幾題的答案你都能順利的回答,那恭喜你!你可以安心地閱讀這篇文章,你一定能看懂!
題目ㄧ. 0.1 + 0.2 = ?
題目二. 1 – 0.9 = ?
題目三. 0.69 x 10 = ?
相信上面三個簡單的十進位數學運算,你的答案應該會跟我一樣吧?
第一題. 0.3
第二題. 0.1
第三題. 6.9
上面應該是無庸置疑的答案,但是如果我們把這三個題目丟給Javascript去運算之後,得到的結果會變成這樣:
第一題. 0.1 + 0.2 = 0.30000000000000004
第二題. 1 – 0.9 = 0.09999999999999998
第三題. 0.69 x 10 = 6.8999999999999995
什麼!?Javascript連這種小學生的算術都會算錯嗎?其實是有原因的,Javascript所有數字都是以64位浮點數形式儲存,也就是所有的數字都會變轉換成二進位。
上面題目中特別有提到這是3個十進位的數學運算,這也就是這個題目的重點,如果今天的題目改成:10 / 3 = 3.3333333333333334 也許你就能比較明白了,也就是說在十進位中要表達 1 / 3 和二進位中表達 1 / 10 一樣困難。
但其實在我們設計網頁的過程中,使用者是沒有二進位觀念的,只在乎運算出來的數值是否符合十進位的結果,這個時候我們可以利用一些技巧來達成正確的結果。
方法1 . 將小數變成整數後再進行運算
第一題. ((0.1 x 10) + (0.2 x 10)) / 10 = 0.3
第二題. ((1 x 10) – (0.9 x 10)) / 10 = 0.1
第三題. ((0.69 x 100) x 10 / 100) = 6.9
雖說以上的方法能夠順利完成任務,但若運算的數值是動態(Dynamic)的,乘數的部分就比較難下,所以我們可以採用第二種方法。
方法2. Math.js(https://mathjs.org/)
透過網站上提供的js,或是透過CDN(https://cdnjs.com/libraries/mathjs)來引入後,透過以下的方法,就可以正確計算出上面三個題目的結果,其中14指的是精準度,通常已經很夠用了。
第一題. math.format(0.1 + 0.2 , 14) = 0.3
第一題. math.format(1 – 0.9 , 14) = 0.1
第一題. math.format(0.69 x 10 , 14) = 6.9
其實Math.js還有很多好用的功能,可以到它官方的網站閱讀一些文章,基本上所有的數學運算應該都可以透過它來玩完成。
boner pills online FastPillsEasy affordable ed medication
cheap ed pills online cheap cialis erectile dysfunction online
рейтинги процессоров для пк [url=http://topcpu.ru]http://topcpu.ru[/url] .
Cheap generic Viagra: FastPillsForMen.com – generic sildenafil
How Nigeria’s biggest city became the world’s hottest winter party destination
casino bonus
It’s a world of endless parties and sleepless nights. A relentless celebration that turns West Africa – and especially Nigeria’s largest city, Lagos – into one of the hottest destinations on the continent, if not the planet, right in the middle of winter.
Detty December is a magical time between December and early January when diaspora communities and tourists flock to Ghana, Nigeria and South Africa for an unforgettable experience filled with flavourful food, soulful African music and sunshine.
Beach parties, festivals and top-tier performances fuel the energy, while fashion takes center stage, with everyone dressing to impress.
Nearly two-thirds of Nigeria’s population is under 25, according to the United Nations Population Fund, making this one of the world’s youngest countries.
Internationally renowned Afrobeats performers and foreign artists make surprise appearances. DJs take to the streets, blasting powerful beats from consoles mounted atop bright yellow minibuses.
At times it’s all-consuming. Good luck getting hair salon appointments, affordable air tickets or navigating Lagos’ already notorious traffic when the party crowds are in town.
Detty December (“detty” is a playful corruption of “dirty”) is a triumphant celebration of culture, music and good vibes that has evolved in recent years during the traditional holidays influx of diaspora returnees, which heightened in 2018 when Ghana ran a launched a successful “Year of Return” campaign actively encouraging people to visit their ancestral homelands.
It’s gathered pace over the past five years, gaining an international reputation, as IJGBs (“I Just Got Backs”) and their friends arrive in batches, eager to unwind and blow off steam after the fast-paced, hard-working year they’ve had overseas.
For many in the vast Nigerian diaspora, it is a deeply personal homecoming, a chance to reconnect with their heritage, traditions and families while immersing themselves in the lively energy of Nigerian life.
Viagra online price: FastPillsForMen – sildenafil online
buying ed pills online: cheap cialis – buy ed meds
какой процессор лучше topcpu.ru .
Thanks , I’ve recently been looking for information about this subject for a long time and yours is the greatest I have discovered so far. But, what in regards to the bottom line? Are you certain in regards to the supply?
http://brandwatches.com.ua/headlight-sealing-for-commercial-vehicles.html
купить диплом о высшем образовании липецк купить диплом о высшем образовании липецк .
I’m really impressed with your writing skills as
well as with the layout on your blog. Is this a paid theme or did you
modify it yourself? Anyway keep up the excellent
quality writing, it is rare to see a great blog like this one nowadays.
сравнение производительности процессоров http://topcpu.ru/ .
диплом купить в москве
сравнение производительности процессоров topcpu.ru .
Generic Cialis without a doctor prescription: buy cialis online – п»їcialis generic
http://maxpillsformen.com/# cheapest cialis
С БК Мелбет выигрывать легко и приятно! Надежная платформа, удобный интерфейс и бонусы для новичков делают игру комфортной. Не откладывайте, начните выигрывать уже сегодня!
рейтинг процессоров intel http://www.topcpu.ru .
http://maxpillsformen.com/# Buy Tadalafil 20mg
i9plok
сравнение процессоров amd https://topcpu.ru/ .
https://fastpillseasy.com/# ed pills
Cheap generic Viagra: buy viagra online – sildenafil over the counter
As a part of the debt administration program, the Sri Lankan government carried out a number of reforms which included the implementation of a brand new Inland Income Act in addition to an computerized fuel pricing method.
http://fastpillsformen.com/# Viagra without a doctor prescription Canada
More popular with the Wall Street crowd, fundamental analysis deals with researching the financial health of a company in relation to its stock price.
Generic Cialis without a doctor prescription Generic Cialis without a doctor prescription Generic Cialis without a doctor prescription
Cialis 20mg price in USA cheapest cialis Generic Cialis without a doctor prescription
cheap ed pills: fast pills easy – ed treatments online
boner pills online cheap cialis generic ed meds online