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還有很多好用的功能,可以到它官方的網站閱讀一些文章,基本上所有的數學運算應該都可以透過它來玩完成。

You may also like...

107,667 Responses

  1. DarrenWab表示:

    gramster.ru gramster.ru пин ап

  2. Jamesboype表示:

    https://gramster.ru/# pinup 2025

  3. DarrenWab表示:

    пин ап Gramster gramster.ru

  4. Jamesboype表示:

    https://gramster.ru/# pinup 2025

  5. WilliamDen表示:

    http://gramster.ru/# gramster.ru

  6. Danielmuh表示:

    Japan’s scenic hot springs town restricting tourists amid fights over the best photo spots
    Автоматизация процесса создания контентных материалов

    Ginzan Onsen, a popular Japanese hot spring town known for its scenic snowy views, has begun limiting entry to day trippers during winter peak season, becoming another destination to tackle overtourism amid the country’s record influx of travelers.

    Located in the Yamagata region about 260 miles north of Tokyo, the onsen is one of the most famous in Japan, drawing around 330,000 visitors each year.

    Travelers from around the world flock to the 300-year-old town during winter not only for a dip in the onsen but its picturesque scenery of traditional Edo-period buildings blanketed in snow – speculated to be the inspiration for Oscar-winning animator Hayao Miyazaki’s film Spirited Away.

    But its popularity has also caused problems for residents in the otherwise tranquil town, with reports of altercations over photo spots and parking places.

    “Many guests became angry (were shouting) over good spots for the purpose of taking pictures, leading to traffic rules being broken, cheating, and making people seek better places and easier ways than others,” the onsen said on its website, regretting that its “vague management” had caused issues.

    Starting January 7, those wanting to enter the onsen town after 5pm will be required to purchase a ticket, according to Ginzan Onsen Information Center. Visitors without bookings at local hotels will be banned after 8pm.

    Tickets, including the bus rides, cost 1150 yen, about $7.

    Those driving themselves will be required to park at a nearby tourist center and use shuttle buses to get into the town.

  7. Jamesboype表示:

    https://gramster.ru/# pinup 2025

  8. _obMn表示:

    увеличение технико экономических показателей https://4dekor.ru/kogda-nuzhno-uvelichenie-tep.html/ .

  9. _hgMn表示:

    работа технического заказчика в строительстве работа технического заказчика в строительстве .

  10. There is just one important tenet to remember when you find yourself considering how you can spend money on stocks with little cash.

  11. The movie grossed $296 million dollars worldwide.

  12. Telegram应用是开源的,Telegram官网下载 https://www.telegramv.net 的程序支持可重现的构建。Telegram同时适用于以下环境:Android安卓端,iPhone 和 iPad及MacOS的Apple端,Windows/Mac/Linux桌面版

  13. DichaelDax表示:

    Ищете идеальный бюстгальтер Бюстгальтер для беременных? Наши женские бюстгальтеры без косточек предлагают комфорт и стиль. Выберите кружевной бюстгальтер для особых случаев или спортивный бюстгальтер для активного образа жизни. Для будущих мам у нас есть бюстгальтеры для беременных и бюстгальтеры для кормления с удобными застежками. Также доступны бюстгальтеры больших размеров и бюстгальтеры с пуш-ап для создания эффектного декольте. Купите лифчик для кормления или бюстгальтер с открытой спиной и наслаждайтесь максимальным комфортом!

  14. WilliamDen表示:

    https://gramster.ru/# pinup 2025

  15. _inMn表示:

    проект планирования территории проект планирования территории .

  16. _lgMn表示:

    работа технического заказчика в строительстве работа технического заказчика в строительстве .

  17. DichaelDax表示:

    This is very interesting, You’re a very skilled blogger. I have joined your feed and look forward to seeking more of your excellent post. Also, I’ve shared your website in my social networks!

    https://smartbuildforum.com.ua/germetik-dlya-avtofar-resheniye-dlya-osveshcheniya-i-zashchity

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。