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

130,346 Responses

  1. Michaelkig表示:

    darknet market links tor marketplace dark market list

  2. DavidCooth表示:

    http://preman69.tech/# Kasino sering memberikan hadiah untuk pemain setia

  3. Michaelkig表示:

    darknet seiten deep web drug store darknet marketplace

  4. Williecrady表示:

    Slot dengan grafis 3D sangat mengesankan http://bonaslot.site/# Banyak kasino menawarkan permainan langsung yang seru

  5. Williecrady表示:

    Slot memberikan kesempatan untuk menang besar http://garuda888.top/# Kasino menyediakan layanan pelanggan yang baik

  6. ThomasThype表示:

    Slot dengan bonus putaran gratis sangat populer: bonaslot.site – BonaSlot

  7. Williecrady表示:

    Kasino di Jakarta memiliki berbagai pilihan permainan https://preman69.tech/# Slot menjadi daya tarik utama di kasino

  8. srochno-zaym表示:

    Каталог финансовых организаций srochno-zaym-online.ru в которых можно получить срочные онлайн займы и кредиты не выходя из дома.

  9. Dannybrelm表示:

    лучшие смотреть кино бесплатно фильмы резка сериалы детективы на телефоне

  10. ThomasThype表示:

    Banyak pemain menikmati jackpot harian di slot: slot88.company – slot 88

  11. DavidCooth表示:

    https://bonaslot.site/# Slot dengan tema film terkenal menarik banyak perhatian

  12. MichaelIncap表示:

    free dark web free dark web tor marketplace

  13. Curtishoike表示:

    Cute baby animals bring visitors to zoos and aquariums. What happens when they grow up?
    арбитраж трафика как начать с нуля
    One of the best things that can happen to a zoo or aquarium is for one of their resident animals to go viral.

    Just look at the multi-hour-long lines to see Moo Deng, a pygmy hippo in Thailand who has become an internet sensation following her July 2024 birth. The sassy animal is now a full-on brand, with Khao Kheow Open Zoo selling Moo Deng merchandise and even releasing a single “by” the hippo in multiple languages.

    Meanwhile, Pesto — a baby king penguin who was eating more fish than his parents by the time he was a few weeks old — is also an online celebrity, with human stars like Olivia Rodrigo and Katy Perry stopping by to meet him.

    But what happens when these cute animals become, well, less cute? The Sea Life Melbourne aquarium has already been planning for the next phase of Pesto’s life — and answering questions from the public about his changing appearance.

    It’s normal for king penguins to lose their feathers by the time they’re about a year old and become confident swimmers. As a result, a spokesperson for the aquarium says, guests have started asking why Pesto looks different — or why they can’t find him at all.

    “We are getting a few guests thinking we have moved him off display completely,” says the spokesperson. “Most of the team’s time is spent pointing him out to guests because he looks so different now.”
    The bottom line is that cute baby animals make money.

    Admission tickets are only the beginning. Many zoos and aquariums offer special “behind the scenes” or “zookeeper for a day” packages at much higher prices. At Sea Life Melbourne, standard entry tickets for adults start at $51, while the Penguin Passport — which include a 45-minute tour of the birds’ area and a look at how their food is prepared — is $199.

    The real jackpot, though, is merchandise. Stuffed animals, T-shirts, fridge magnets, keychains, kids’ books and other branded products are a major way for zoos and aquariums to make money.

  14. srochno-zaym表示:

    Каталог финансовых организаций https://srochno-zaym-online.ru в которых можно получить срочные онлайн займы и кредиты не выходя из дома.

  15. Dannyfut表示:

    deep dark web dark web link darkmarket

  16. Kevinalgon表示:

    Scores of unexploded World War II bombs discovered under children’s playground
    бот лаки джет
    Scores of unexploded bombs dating from World War II have been recovered from a children’s playground in northern England after a chance discovery.

    Local officials in the town of Wooler, Northumberland called in bomb disposal experts after workers involved in a planned overhaul of Scotts Play Park found unexploded ordnance, the parish council said in a statement sent to CNN on Monday.

    Two bombs were initially removed by the British Army, the UK Ministry of Defense said in a statement. The parish council was then advised that a full survey of the area was required, according to a council spokesperson.
    Bomb disposal company Brimstone Site Investigation then uncovered 65 10-pound practice bombs and smoke cartridges on the first day of works, with a further 90 practice bombs recovered on the second day.

    The company told CNN that the bombs date from World War II.

    According to the parish council, all of the bombs need to be found and removed before the park can be reopened. It said 174 devices had been found so far.

  17. Phillipedugs表示:

    Look of the Week: Kendrick Lamar’s Super Bowl pants signal the return of flares
    kraken shop
    This year’s Super Bowl halftime show was hardly a fashion extravaganza, with headliner Kendrick Lamar keeping things simple in a backwards cap and motorbike-style varsity jacket, which he kept on throughout.

    And without the costume-change roulette we’ve come to expect of halftime shows, the internet fixated on one item in particular: his jeans.

    While not quite the bell-bottoms of decades past (the 1970s and the 2000s, specifically), the Compton-born rapper’s washed denim pants flared out at the knee and dragged beneath his heels along the stage at Caesars Superdrome in New Orleans. His silhouette stood in stark contrast to that of record producer Mustard, who made a brief cameo in a pair of outsized jeans straight from the West Coast hip-hop playbook.
    Opinions were, as ever, divided on social media. Some users described Lamar’s flares as “women’s jeans” and “Hannah Montana pants,” earning him comparisons to everyone from Jennifer Aniston to country singer Lainey Wilson. Others joked that their moms were looking for a similar pair or that they nodded to millennials, for whom flares were a teenage staple.

    But those suggesting his style was outdated, or gender-inappropriate, may not have been paying attention to the recent resurgence of flares — in both womenswear and menswear. After all, Lamar’s jeans were designed by one of the most influential figures in modern fashion, Celine’s former creative director Hedi Slimane, before he departed the French label in October.

  18. DavidCooth表示:

    https://slotdemo.auction/# Kasino selalu memperbarui mesin slotnya

  19. Aaronbus表示:

    preman69 slot preman69 Mesin slot menawarkan berbagai tema menarik

  20. Dannybrelm表示:

    резка фэнтези новинки full hd смотреть боевики онлайн Netflix 2025

  21. srochno-zaym表示:

    Каталог финансовых организаций https://srochno-zaym-online.ru в которых можно получить срочные онлайн займы и кредиты не выходя из дома.

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

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