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,689 Responses

  1. Robertengep表示:

    https://easyrxindia.com/# online shopping pharmacy india

  2. Robertengep表示:

    http://mexstarpharma.com/# mexican drugstore online

  3. Профессиональный сервисный центр по ремонту квадрокоптеров и радиоуправляемых дронов.
    Мы предлагаем:ремонт квадрокоптеров с гарантией
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  4. Mazrmzo表示:

    Привет!
    Как быстро получить диплом магистра? Легальные способы
    btpars.com/home.php?mod=space&uid=2590613

  5. Peterhew表示:

    indian pharmacy: best india pharmacy – best online pharmacy india

  6. создание и продвижение сайтов москва http://prodvizhenie-sajtov-v-moskve213.ru/ .

  7. JeremyPsymn表示:

    http://easyrxcanada.com/# legit canadian pharmacy

  8. Профессиональный сервисный центр по ремонту сотовых телефонов, смартфонов и мобильных устройств.
    Мы предлагаем: ремонт телефонов
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  9. Lazrkfv表示:

    Здравствуйте!
    Мы изготавливаем дипломы любой профессии по разумным тарифам.
    terasinomasa.club/diplom-243754ugait

  10. Eanrhbo表示:

    Привет!
    Мы изготавливаем дипломы любых профессий по доступным тарифам.
    roomblock.com/send-rfp

  11. Hermanswoff表示:

    best rated canadian pharmacy: canadian drugs pharmacy – rate canadian pharmacies

  12. Профессиональный сервисный центр по ремонту сотовых телефонов, смартфонов и мобильных устройств.
    Мы предлагаем: где можно починить телефон
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  13. Robertengep表示:

    https://mexstarpharma.online/# п»їbest mexican online pharmacies

  14. WilliamDeeli表示:

    Привет!
    Мы изготавливаем дипломы.
    ruhfhshj.gallery.ru

  15. создание и продвижение сайтов в москве создание и продвижение сайтов в москве .

  16. JeremyPsymn表示:

    https://easyrxindia.com/# online pharmacy india

  17. Terima kasih atas artikel yang bermanfaat. Semangat dari IDProperti.com | Pasang Iklan Properti Gratis

  18. Check out my website – Daycare Near Me

  19. Peterhew表示:

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

  20. Mazrpid表示:

    Привет, друзья!
    Легальная покупка школьного аттестата с упрощенной программой обучения
    cekresipos.com

  21. Peterhew表示:

    online pharmacy india: indian pharmacy online – best india pharmacy

  22. Stephenideox表示:

    There is no single ideal jurisdiction in the world for starting a business that would suit everyone. But there are countries whose legislative and tax system is ideally suited to your particular case.
    Very often we are approached by clients with the request “Quickly register a company in the EU and pay low taxes”. But during a consultation with a specialist it turns out that, for example, the client also wants to stay in the country of business for a longer period of time or permanently reside there with the possibility of obtaining EU citizenship, which means that it is necessary to additionally apply for a long-term residence permit abroad.
    In view of this situation, we always recommend approaching the choice of a country for starting a business comprehensively, taking into account both corporate, tax and immigration laws together with the goals and objectives that the entrepreneur wants to achieve.

  23. Peterhew表示:

    canada pharmacy 24h: canadian pharmacy 1 internet online drugstore – canadian pharmacy 365

  24. Stephenideox表示:

    Costs of business registration and further maintenance of the company
    When choosing a country for business registration, it is important to be aware in advance of the minimum required authorised capital for different types of companies, the average salary for hiring employees, the cost of office rent, the cost of banking services, etc.
    No foreign jurisdiction on blacklists
    Blacklists are maintained by international organisations as well as individual countries. For example, if a jurisdiction is included in the EU blacklist or is considered offshore, it complicates the country’s financial relations with the EU. In this case, European banks will be forced to conduct additional checks when dealing with companies registered in EU blacklisted countries.
    Fast and convenient air connections to the country of residence
    This factor is also very important. For example, you decide to open a company in Hong Kong, Singapore or Seychelles and the remoteness of these jurisdictions may create certain difficulties for the entrepreneur.

  25. GlennSaunk表示:

    Opening a bank account for a company in Europe can be challenging due to strict anti-money laundering and counter-terrorist financing requirements. Banks require extensive documentation, including proof of business model and origin of funds. It is also important to consider that many banks require the personal presence of the founder when opening an account.
    Step 4: Tax planning
    Once a company has been incorporated and a bank account opened, attention should be paid to tax planning. This includes selecting the best tax scheme, possible tax incentives and examining any double tax treaties that may exist between the country of incorporation and other countries where the business is planned to operate.
    Step 5: Compliance with legal requirements
    The company must comply not only with tax regulations, but also with other legal regulations, including labour, health and safety and industrial safety laws. It is important to regularly consult with local legal counsel to maintain compliance with all requirements.
    Conclusion: Opening a company in Europe with a bank account requires careful planning and preparation. Understanding local laws, choosing the right jurisdiction and complying with all regulatory requirements are key elements of success in this process. It is advisable to seek professional assistance from international business and tax experts to ensure a smooth start of your business in Europe.

  26. Xazrpit表示:

    Добрый день!
    Заказать документ о получении высшего образования.
    Мы предлагаем дипломы любой профессии по приятным тарифам.
    svadba-club.ru
    Рады помочь!.

  27. Hermanswoff表示:

    mexican rx online: buying from online mexican pharmacy – mexican pharmacy

  28. Xazrugc表示:

    Здравствуйте!
    Заказать документ о получении высшего образования.
    Мы предлагаем дипломы психологов, юристов, экономистов и любых других профессий по выгодным тарифам.
    zenfiramed.ru
    Рады помочь!.

發佈留言

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