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

125,166 Responses

  1. Jamesavata表示:

    пинап казино – pinup 2025

  2. JesseDex表示:

    пин ап казино: https://pinupkz.life/

  3. JesseDex表示:

    pinup 2025: https://pinupkz.life/

  4. KevinPsync表示:

    Struggling to lose weight? AquaSculpt is transforming weight loss with its natural, fast-acting capsules. Packed with proven AquaSculpt ingredients, these capsules burn fat, boost energy, and deliver real AquaSculpt results in weeks. Curious about AquaSculpt reviews? Users love its effectiveness and zero AquaSculpt side effects. Want to know AquaSculpt how to use? It’s simple—take daily and watch the pounds melt away. Ready to try? AquaSculpt buy now at http://aquasculpt.xyz and sculpt your dream body today!

  5. Forrestteaxy表示:

    AquaSculpt weight loss is here to stay! With AquaSculpt capsules, you get fast AquaSculpt results thanks to natural AquaSculpt ingredients. No worries about AquaSculpt side effects—users confirm it in AquaSculpt reviews. Curious AquaSculpt how to use? It’s easy and effective. AquaSculpt where to buy? Visit http://aquasculpt.one and transform your body now!

  6. Dewayneepics表示:

    Say hello to AquaSculpt—a game-changer in weight loss! These AquaSculpt capsules use natural AquaSculpt ingredients to shed pounds and boost confidence. No AquaSculpt side effects, just pure AquaSculpt results—see why in AquaSculpt reviews. Learn AquaSculpt how to use and join thousands who love it. AquaSculpt buy today at http://aquasculpt.lifestyle !

  7. TracyRak表示:

    Struggling to lose weight? AquaSculpt is transforming weight loss with its natural, fast-acting capsules. Packed with proven AquaSculpt ingredients, these capsules burn fat, boost energy, and deliver real AquaSculpt results in weeks. Curious about AquaSculpt reviews? Users love its effectiveness and zero AquaSculpt side effects. Want to know AquaSculpt how to use? It’s simple—take daily and watch the pounds melt away. Ready to try? AquaSculpt buy now at http://aquasculpt.me and sculpt your dream body today!

  8. Jamesavata表示:

    пин ап казино зеркало – пин ап зеркало

  9. CharlesBrato表示:

    Say hello to AquaSculpt—a game-changer in weight loss! These AquaSculpt capsules use natural AquaSculpt ingredients to shed pounds and boost confidence. No AquaSculpt side effects, just pure AquaSculpt results—see why in AquaSculpt reviews. Learn AquaSculpt how to use and join thousands who love it. AquaSculpt buy today at http://aquasculpt.best

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

  11. JesseDex表示:

    pinup 2025: https://pinupkz.life/

  12. Williamuniot表示:

    pinup 2025 – пин ап казино официальный сайт

  13. Dewayneepics表示:

    AquaSculpt weight loss is here to stay! With AquaSculpt capsules, you get fast AquaSculpt results thanks to natural AquaSculpt ingredients. No worries about AquaSculpt side effects—users confirm it in AquaSculpt reviews. Curious AquaSculpt how to use? It’s easy and effective. AquaSculpt where to buy? Visit http://aquasculpt.lifestyle and transform your body now!

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

  15. CharlesBrato表示:

    Struggling to lose weight? AquaSculpt is transforming weight loss with its natural, fast-acting capsules. Packed with proven AquaSculpt ingredients, these capsules burn fat, boost energy, and deliver real AquaSculpt results in weeks. Curious about AquaSculpt reviews? Users love its effectiveness and zero AquaSculpt side effects. Want to know AquaSculpt how to use? It’s simple—take daily and watch the pounds melt away. Ready to try? AquaSculpt buy now at http://aquasculpt.best and sculpt your dream body today!

  16. Jamesavata表示:

    пинап казино – пин ап казино официальный сайт

  17. JesseDex表示:

    пин ап вход: https://pinupkz.life/

  18. Danieljak表示:

    “Every morning I come downstairs and he’s already done the dishwasher, he’s already packed his lunch, and he’s ready to go,” Ruthe’s father, Ben, tells CNN Sports.

    “He’s just a disciplined kid. He goes to bed early, he looks after himself, he eats well, he looks after his sister. He’s just a good kid around the house in all ways, really. We’re very lucky.”
    pendle finance
    Ruthe is next due to compete in the 1,500 meters at the Maurie Plant Meet in Melbourne on Saturday, and one target time to aim for will be his dad’s fastest time of 3:41.22 – three hundredths of a second faster than Ruthe’s current personal best.
    But he still has a way to go before he can call himself the most decorated runner in his family. Dad Ben and mom Jess are both former national champions who represented New Zealand on the world stage, while his maternal grandparents won European championship medals for Great Britain.

    His grandmother, Rosemary Stirling, arguably had the most impressive achievement: an 800m Commonwealth Games title from 1970.

    Despite his family pedigree, Ruthe was never under any pressure to take running seriously. His parents, in fact, didn’t allow him or his sister Daisy to train at all until they were 13, never wanting their identities to be tied solely to running.

    “It feels like it’s the right decision about now,” says Ben.

    But as he gradually starts to realize his potential, Ruthe, when pushed, admits to having big goals in the sport.

    “If I had to pick one thing, definitely Olympic gold,” he says. “I feel like that’s most runners’ dream and the biggest thing you can actually win. So that’ll definitely be the top of my bucket list.”
    The 2032 Olympics in Brisbane, Ruthe adds, would be a nice target. And as for the Los Angeles Games in three years’ time? “I’d actually love to try and qualify for LA 28,” he says. “I feel like that’ll be a tough goal. But if I do that, I’ll be really happy.”

    Already, Ruthe’s name is being mentioned in the same breath as Norway’s Jakob Ingebrigtsen, the most successful middle-distance of this generation. It was his record as the youngest-ever four-minute miler that Ruthe took last week, and the New Zealander also beat Ingebrigtsen’s 1,500m record for a 15-year-old earlier this year.

    Ingebrigtsen’s success, Ruthe says, has given him hope that he too can “have a good future” in the sport. But his biggest source of motivation comes not from the two-time Olympic champion, but from those closest to him – his training group led by coach Craig Kirkwood and athlete Sam Tanner.

    The pair were instrumental in Ruthe’s recent mile time of 3:58.35, and it was five-time national champion Tanner who paced him perfectly around four laps of the track on his way to the record.

  19. Williamuniot表示:

    пинап казино – пин ап вход

  20. Williamuniot表示:

    pinup 2025 – пин ап

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

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