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

102,494 Responses

  1. WayneCoirl表示:

    mexican pharmaceuticals online: mexico drug stores pharmacies – medicine in mexico pharmacies

  2. Arnoldten表示:

    mexico pharmacies prescription drugs medication from mexico pharmacy pharmacies in mexico that ship to usa

  3. DominicJaw表示:

    mexican online pharmacies prescription drugs: medication from mexico pharmacy – mexican rx online

  4. Nelsonbluck表示:

    medicine in mexico pharmacies: п»їbest mexican online pharmacies – medicine in mexico pharmacies

  5. Nelsonbluck表示:

    medication from mexico pharmacy: mexican online pharmacies prescription drugs – mexico pharmacies prescription drugs

  6. Lazrozi表示:

    Привет!
    Купить диплом университета.
    a90275db.beget.tech/2024/07/04/kak-podobrat-proverennyy-magazin-s-ogromnym-katalogom-diplomov

  7. Diplomi_zgEa表示:

    Привет!
    Купить документ университета вы имеете возможность в нашем сервисе.
    ast-diplom.com/kupit-diplom-s-registraciej

  8. Reent表示:

    The Range Rover Sport 2016 comes with a 3.0L V-6 Engine, 8-spd w OD transmission, 340 @ 6,500 rpm horsepower, and 332 @ 3,500 rpm torque. It’s also equipped with a terrain response four-wheel drive type, SIRIUS AM FM HD Satellite, seek-scan radio, and rear fog driving lights, making it a remarkable choice enhance your journey to its best level. It features USB and audio input, Bluetooth, air conditioning, and GPS navigation as well. We offer this charming model in a pure white shade that comes with a red black interior. With Range Rover Rental Dubai, you’ll see the world’s excellence as you’ve never seen it before. Contact us at VIP Car Rental to rent your fancied Range Rover. Entrusting Alif Car Rental with your transportation needs in Dubai brings forth several advantages:
    http://koewa.or.kr/bbs/board.php?bo_table=free&wr_id=18135
    1. Experienced Drivers: GCC Drive’s drivers are not just skilled behind the wheel; they are knowledgeable about Dubai’s landmarks and can offer valuable insights during your journey. World-class chauffeur services can always make your rides smooth and easy. Fulfill your only riding needs by booking a driver on monthly basis by Safer Driver UAE. . Any type of driver services, whether it’s personal drivers for corporate vehicles, fleet management, vehicle transfers, shuttle drivers, or other business transportation solutions. Dubai is a beautiful city located in the Persian Gulf region, known for its luxury chauffeur service and chauffeur-driven car hire options. It serves as the largest and busiest transit hub for passengers traveling between Europe and Central Asia, as well as the Gulf countries, in both directions. The city boasts numerous entertainment options, tourist attractions, and a vibrant nightlife scene. Whether you need a private driver in Dubai, monthly chauffeur service dubai, or luxury car taxi service, Dubai has it all.

  9. Trefgpd表示:

    Добрый день!
    Купить диплом о среднем образовании в Москве и любом другом городе
    jubileetrip.com/2024/07/12/купить-диплом-проверенные-способы
    Рады оказать помощь!.

  10. Reent表示:

    View the full range of cars available from eZhire. Our large fleet includes everything from small hatchbacks to large SUVs and exotic supercars. Get your rent a car in Al Barsha 1 Dubai by calling us today or sending us an inquiry. Casual, relaxing and at ease outdoor experience .Light Fare with healthy food options including sandwiches and quick bites and mouthwatering smoothies You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page. Services Enjoy the flexibility of having a car without long-term commitments of ownership or leasing, all paid in monthly instalments. Festival City and Motor City are the cheapest neighbourhoods to hire a car in Dubai. We found that Autostrad Rent A Car is the cheapest car hire company in Festival City with an average cost of £10 day. Budget is the most affordable hire company in Motor City with prices averaging £11 day.
    https://co-roma.openheritage.eu/profiles/clutolancom1983/activity
    Your safety is guaranteed. This is because our cars are meticulously maintained. Hence, you are assured of a hitch-free journey. We make sure our cars receive routine maintenance, as we do with all of our vehicles, to guarantee the highest safety standards. This ensures the cars operate to their fullest potential and maintains our fleet’s high level of functionality. This dedication to dependable, comprehensive service keeps us at the top of the Dubai car rental market. Send us an inquiry to get a Toyota monthly rental plan or long-term package, and we’ll take it from there. In terms of hiring a Toyota in Dubai, Kohistan Rent a Car is a dependable and trustworthy option. Here’s why you should consider renting a Toyota from Kohistan Rent a Car: The Toyota Corolla has been a stalwart of the Toyota fleet for decades, and the latest model is better than ever. The 2020 Corolla is a whole new animal, with both petrol-only and Hybrid options to choose from. We’re delighted to welcome the Corolla back into our fleet, and we know our Toyota-loving customers are pleased to see its return, too.

  11. Arnoldten表示:

    mexican pharmaceuticals online mexican drugstore online buying prescription drugs in mexico online

  12. световое оборудование для актового зала световое оборудование для актового зала .

  13. RobinHig表示:

    продвижение москва https://sozdanie-sajtov-pod-klyuch.ru/

  14. WayneCoirl表示:

    mexican border pharmacies shipping to usa: best online pharmacies in mexico – pharmacies in mexico that ship to usa

  15. DominicJaw表示:

    mexican online pharmacies prescription drugs: best online pharmacies in mexico – buying prescription drugs in mexico online

  16. акустическое оборудование для актового зала акустическое оборудование для актового зала .

  17. WayneCoirl表示:

    reputable mexican pharmacies online: mexican rx online – mexico drug stores pharmacies

  18. Arnoldten表示:

    medicine in mexico pharmacies mexico drug stores pharmacies buying prescription drugs in mexico online

  19. DominicJaw表示:

    mexican mail order pharmacies: best online pharmacies in mexico – purple pharmacy mexico price list

  20. Nelsonbluck表示:

    buying prescription drugs in mexico online: buying prescription drugs in mexico online – buying from online mexican pharmacy

  21. Nelsonbluck表示:

    mexican pharmaceuticals online: mexico drug stores pharmacies – mexico drug stores pharmacies

  22. sto_spei表示:

    Откройте для себя Оболонь: сердце Киева, в атмосферу.
    Оболонь: гастрономический рай, точки.
    Оболонь: идеальное место для жизни, познакомьтесь.
    Оболонь: активный отдых и развлечения, новые.
    Откройте для себя набережную Оболони, проведите время.
    Оболонь с детьми: идеи для досуга, заведения.
    Разнообразие традиций на Оболони, познайте.
    Лучшие бары и клубы на Оболони, заведения.
    Отдых на природе в Оболони: куда пойти?, наслаждайтесь.
    Исторические памятники Оболони, уникальные.
    Какова Оболонь сегодня?, с новыми данными.
    Ассоциации с Оболонью: что приходит на ум?, изучите.
    Гастрономическое путешествие по Оболони, узнайте.
    Развлечения для подростков на Оболони, модные.
    Что делать на Оболони летом?, уникальные.
    Как добраться до Оболони?, исследуйте.
    Путеводитель по Оболони: что стоит знать, разберитесь.
    Оболонь: от старинных улиц до современных зданий, с историей.
    сто київ https://stoobolongfg.kiev.ua/ .

發佈留言

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