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

101,055 Responses

  1. GeorgeGailt表示:

    The golf https://arabic.golfclub-ar.com industry in the Arab world is growing rapidly, attracting players from all over the world.

  2. Uazrvua表示:

    Привет!
    Приобрести диплом о высшем образовании.
    fotomaniya.getbb.ru/viewtopic.php?f=16&t=11163

  3. Eanrwdt表示:

    Здравствуйте!
    Мы изготавливаем дипломы любых профессий по доступным тарифам.
    andersonobserver.squarespace.com/news/2017/4/12/library-sponsors-april-poetry-contest.html

  4. Altoncok表示:

    Tributes flood in for BBC sport commentator whose wife and daughters were killed in suspected crossbow attack
    русский анальный секс

    Figures from across the United Kingdom have offered their condolences to a BBC sport commentator, after his wife and two daughters were killed by an alleged crossbow attacker, in deaths that again drew attention to the epidemic of violence against women.

    Carol Hunt, 61, wife of BBC horse racing commentator, John Hunt, and their daughters, Hannah Hunt, 28, and Louise Hunt, 25, died from injuries sustained in an attack in Bushey, just northwest of London, on Tuesday, according to police and Britain’s public broadcaster.

    A 26-year-old suspect wanted in connection with the killings, and named as Kyle Clifford, was found by British police in Enfield, north London, on Wednesday, following a sprawling manhunt. There were no previous reports to the force over Clifford, who is in serious condition in hospital and is yet to speak with officers, Hertfordshire Police said in a statement.

    A crossbow was recovered as part of the investigation, which police believe was used in a “targeted incident.”
    Epidemic of violence against women
    The killings of the three women rocked Britain, where mass murders are infrequent but violence against women and girls has been officially labeled as a national threat.

    A woman is killed by a man every three days in the UK and one in four women will experience domestic violence in her lifetime, the United Nations’ special rapporteur on violence against women and girls, Reem Alsalem, said earlier this year.

    Charities and human rights organizations have subsequently reiterated urgent demands to tackle femicide in the UK.

  5. PedroVef表示:

    стул изо черный кожзам https://office-mebel-on-msk.ru/

  6. Lariorwjd表示:

    Можно ли быстро купить диплом старого образца и в чем подвох?
    diploms-x24.ru/kupit-diplom-voronezh

  7. Lariorvwh表示:

    Полезные советы по безопасной покупке диплома о высшем образовании
    ast-diploms.com/kupit-diplom-omsk

  8. Qazrxkg表示:

    Привет, друзья!
    Сколько стоит диплом высшего и среднего образования и как его получить?.
    Приобрести диплом о высшем образовании.
    http://www.rugladyseminars.com/cb-profile/pluginclass/cbblogs?action=blogs&func=show&id=409

  9. Sazrpzc表示:

    Здравствуйте!
    Как получить диплом техникума с упрощенным обучением в Москве официально
    fish-sea-products.ru/forum/user/5837
    Всегда вам поможем!

  10. Sazrixv表示:

    Привет, друзья!
    Мы можем предложить дипломы психологов, юристов, экономистов и других профессий по доступным ценам. Цена зависит от определенной специальности, года выпуска и университета. Всегда стараемся поддерживать для покупателей адекватную ценовую политику. Для нас важно, чтобы дипломы были доступны для большого количества наших граждан.
    weekevents.ru/diplom-vashego-vyibora-zhdet-vas-sdelayte-svoy-zakaz-pryamo-seychas

  11. ThomasDet表示:

    http://ciprodelivery.pro/# where can i buy cipro online

  12. Uazrasz表示:

    Привет, друзья!
    Где приобрести диплом специалиста?
    my.omsystem.com/members/anthonyjoseph

  13. Uazraay表示:

    Добрый день!
    Где заказать диплом специалиста?
    zomi.net/read-blog/28389

  14. Cazrdrh表示:

    Добрый день!
    Мы готовы предложить документы техникумов, которые расположены на территории всей РФ. Вы можете купить качественный диплом за любой год, указав актуальную специальность и оценки за все дисциплины. Документы выпускаются на “правильной” бумаге самого высокого качества. Это дает возможность делать настоящие дипломы, которые невозможно отличить от оригиналов. Они заверяются необходимыми печатями и подписями.
    forosmex.com/index.php?/gallery/image/547-%D0%BF%D0%BE%D0%BA%D1%83%D0%BF%D0%B0%D0%B5%D0%BC-%D0%B4%D0%BE%D0%BA%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D0%B2-%D0%BB%D1%83%D1%87%D1%88%D0%B5%D0%BC-%D0%BC%D0%B0%D0%B3%D0%B0%D0%B7%D0%B8%D0%BD%D0%B5-%D0%BF%D0%BE-%D0%BA%D0%BE%D0%BC%D1%84%D0%BE%D1%80%D1%82%D0%BD%D0%BE%D0%B9-%D1%86%D0%B5%D0%BD%D0%B5/

  15. Danrpma表示:

    Привет!
    Мы изготавливаем дипломы любой профессии.
    pro-eltern.de/read-blog/145_hotite-zakazat-attestat-u-nadezhnogo-proizvoditelya-zhdem-vas.html
    Рады помочь!.

  16. Danraey表示:

    Привет, друзья!
    Мы изготавливаем дипломы любой профессии.
    newmedtime.ru/vyisshee-obrazovanie-za-sutki-legalno-i-nadezhno
    Рады оказаться полезными!.

  17. Dnrtpov表示:

    Привет!
    Купить документ о получении высшего образования можно в нашей компании.
    ast-diplom.com/kupit-diplom-o-srednem-obrazovanii
    Удачи!

  18. Diplomi_nzEa表示:

    купить диплом спо diploms-x.com .

  19. Diplomi_fzEa表示:

    купить диплом средняя окончание diploms-x.com .

  20. Diplomi_enEa表示:

    Здравствуйте!
    Приобрести документ института можно в нашей компании.
    diplomasx.com/kupit-diplom-kazan 

  21. JamesBak表示:

    doxycycline cost in mexico: best price for doxycycline 100 mg without prescription – doxycycline capsules 100mg price

  22. generic表示:

    [url=http://xmodafinil.com/]where to buy provigil[/url]

  23. Sazrert表示:

    Привет!
    Полезные советы по покупке диплома о высшем образовании без риска
    enriquerp.listbb.ru/viewtopic.php?f=4&t=429
    Будем рады вам помочь!

  24. Jeffreyovemi表示:

    Manny Pacquiao https://filipino-boxer.manny-pacquiao-ar.com is one of the most prominent boxers in the history of the sport.

  25. KeithDup表示:

    Mike Tyson https://american-boxer.mike-tyson-ar.com one of the most famous and influential boxers in history, was born on June 30, 1966 in Brooklyn, New York.

  26. HerbertMerge表示:

    Muhammad Ali https://american-boxer.muhammad-ali-ar.com is perhaps one of the most famous and greatest athletes in the history of boxing.

發佈留言

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