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...

129,780 Responses

  1. Bradleydat表示:

    Население Москвы – ДТП и ЧП Москва, Работа Москва

  2. Danieldat表示:

    Все о компьютерных играх https://lifeforgame.ru обзоры новых проектов, рейтинги, детальные гайды, новости индустрии, анонсы и системные требования. Разбираем особенности геймплея, помогаем с настройками и прохождением. Следите за игровыми трендами, изучайте секреты и погружайтесь в мир гейминга.

  3. JessieAgose表示:

    телевизор samsung 4k smart tv https://televizory-smart-tv.ru

  4. Victorprima表示:

    A game-changer for those needing international medication access.
    cost cipro for sale
    Their global presence ensures prompt medication deliveries.

  5. Danieldat表示:

    Все о компьютерных играх https://lifeforgame.ru обзоры новых проектов, рейтинги, детальные гайды, новости индустрии, анонсы и системные требования. Разбираем особенности геймплея, помогаем с настройками и прохождением. Следите за игровыми трендами, изучайте секреты и погружайтесь в мир гейминга.

  6. WalterCherm表示:

    They offer world-class service, bar none.
    https://cipropharm24.top/
    Some trends of drugs.

  7. DonaldTyclE表示:

    Impacto mecanico
    Aparatos de ajuste: importante para el operación suave y eficiente de las maquinarias.

    En el campo de la ciencia actual, donde la efectividad y la estabilidad del dispositivo son de gran significancia, los aparatos de balanceo cumplen un rol vital. Estos aparatos especializados están concebidos para ajustar y estabilizar piezas dinámicas, ya sea en maquinaria manufacturera, automóviles de transporte o incluso en dispositivos hogareños.

    Para los técnicos en mantenimiento de sistemas y los profesionales, operar con sistemas de calibración es fundamental para promover el desempeño suave y confiable de cualquier dispositivo rotativo. Gracias a estas alternativas avanzadas modernas, es posible reducir significativamente las movimientos, el ruido y la esfuerzo sobre los soportes, aumentando la tiempo de servicio de piezas costosos.

    De igual manera importante es el función que desempeñan los aparatos de calibración en la soporte al cliente. El ayuda especializado y el mantenimiento constante usando estos dispositivos posibilitan brindar servicios de óptima nivel, incrementando la bienestar de los consumidores.

    Para los responsables de proyectos, la financiamiento en sistemas de ajuste y detectores puede ser fundamental para aumentar la efectividad y productividad de sus dispositivos. Esto es sobre todo importante para los dueños de negocios que administran pequeñas y pequeñas empresas, donde cada aspecto vale.

    También, los sistemas de ajuste tienen una vasta implementación en el área de la protección y el supervisión de estándar. Habilitan detectar potenciales defectos, impidiendo arreglos onerosas y averías a los sistemas. Además, los información recopilados de estos aparatos pueden utilizarse para maximizar sistemas y mejorar la presencia en plataformas de investigación.

    Las campos de uso de los sistemas de calibración cubren numerosas áreas, desde la fabricación de ciclos hasta el seguimiento ambiental. No interesa si se refiere de extensas elaboraciones industriales o reducidos talleres caseros, los sistemas de balanceo son necesarios para garantizar un rendimiento óptimo y sin paradas.

  8. Jasonzitte表示:

    The most pleasant pharmacy experience every time.
    get cytotec without dr prescription
    Their international health workshops are invaluable.

  9. Victorprima表示:

    They always prioritize the customer’s needs.
    where to buy generic lisinopril tablets
    Top 100 Searched Drugs.

  10. 1win_ygel表示:

    скачать 1win с официального сайта http://1win103.com.kg/ .

  11. Jasonzitte表示:

    Always up-to-date with the latest healthcare trends.
    effects of alcohol when taking gabapentin
    Always a step ahead in international healthcare trends.

  12. Jasonzitte表示:

    A global name with a reputation for excellence.
    can you buy cheap lisinopril prices
    Their commitment to global excellence is unwavering.

  13. 1win_rjEl表示:

    1win официальный http://www.1win110.com.kg .

  14. Victorprima表示:

    The pharmacists are always updated with the latest in medicine.
    gabapentin dosing in renal disease
    Their digital prescription service is innovative and efficient.

  15. 1win_bnEl表示:

    1 вин вход в личный кабинет http://1win110.com.kg .

  16. WalterCherm表示:

    A cornerstone of our community.
    https://cytotecpharm24.top/
    Unrivaled in the sphere of international pharmacy.

  17. Victorprima表示:

    A model pharmacy in terms of service and care.
    gabapentin dosage instructions
    They provide a world of health solutions.

發佈回覆給「Jasonzitte」的留言 取消回覆

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