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

131,176 Responses

  1. Kevinalgon表示:

    Scores of unexploded World War II bombs discovered under children’s playground
    bot lucky jet
    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.

  2. Phillipedugs表示:

    Look of the Week: Kendrick Lamar’s Super Bowl pants signal the return of flares
    kraken сайт
    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.

  3. ThomasThype表示:

    Beberapa kasino memiliki area khusus untuk slot: slot demo – akun demo slot

  4. Williecrady表示:

    Pemain sering mencoba berbagai jenis slot http://preman69.tech/# Slot modern memiliki grafik yang mengesankan

  5. Williecrady表示:

    Kasino di Jakarta memiliki berbagai pilihan permainan https://slot88.company/# Banyak kasino memiliki program loyalitas untuk pemain

  6. DavidCooth表示:

    http://slot88.company/# Slot klasik tetap menjadi favorit banyak orang

  7. JamesLok表示:

    Mesin slot digital semakin banyak diminati http://garuda888.top/# Kasino di Indonesia menyediakan hiburan yang beragam

  8. Williecrady表示:

    Banyak kasino memiliki program loyalitas untuk pemain http://slotdemo.auction/# Kasino memastikan keamanan para pemain dengan baik

  9. Aaronbus表示:

    slot demo rupiah slot demo Banyak kasino memiliki program loyalitas untuk pemain

  10. Rodneytus表示:

    dark websites darknet drug store black internet

  11. Kevinjef表示:

    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.

  12. Kennethphink表示:

    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.

  13. MichaelDromb表示:

    Look of the Week: Kendrick Lamar’s Super Bowl pants signal the return of flares
    kra28 cc
    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.

  14. Rodneytus表示:

    deep web links darkmarket deep web search

  15. ThomasThype表示:

    п»їKasino di Indonesia sangat populer di kalangan wisatawan: slot demo rupiah – demo slot pg

  16. DavidCooth表示:

    http://bonaslot.site/# Pemain sering mencoba berbagai jenis slot

  17. ThomasThype表示:

    Banyak pemain menikmati bermain slot secara online: preman69 – preman69.tech

  18. DavidCooth表示:

    http://garuda888.top/# Slot menjadi bagian penting dari industri kasino

  19. Michaelkig表示:

    deep web drug url tor market url darknet search engine

  20. DerekMax表示:

    click here to read https://toastwallet.org/

  21. DerekMax表示:

    go to this site https://web-martianwallet.io

  22. MichaelIncap表示:

    tor market links dark web search engine darkmarket 2025

  23. JamesLok表示:

    Mesin slot menawarkan berbagai tema menarik http://preman69.tech/# Mesin slot digital semakin banyak diminati

  24. Frankelava表示:

    Welcome to PancakeSwap: A Beginner’s Guide
    PancakeSwap is a decentralized exchange platform on the Binance Smart Chain, designed for swapping BEP-20 tokens. With its vibrant ecosystem, ease of use, and low transaction fees, it’s become a popular choice among crypto enthusiasts.
    Pancakeswap exchange
    What is PancakeSwap?
    PancakeSwap is an automated market maker (AMM) that allows users to trade directly from their crypto wallets. There’s no order book involved; instead, trades are made against a liquidity pool. Here’s how you can get started:

    How to Use PancakeSwap?
    Set Up Your Wallet
    First, you need a crypto wallet like MetaMask or Trust Wallet. Ensure your wallet supports BEP-20 tokens.
    Connect to Binance Smart Chain
    Configure your wallet to connect to the Binance Smart Chain network. Detailed guides are available in your wallet settings.
    Purchase BNB
    You’ll need BNB (Binance Coin) to cover transaction fees. Buy BNB from a reputable exchange and transfer it to your wallet.
    Access PancakeSwap
    Visit the official PancakeSwap website and connect your wallet by clicking on the ‘Connect Wallet’ button.
    Start Trading
    Once connected, you can begin swapping BEP-20 tokens. Choose the tokens you wish to trade and confirm your transactions.
    Benefits of PancakeSwap
    Lower Fees: Operating on Binance Smart Chain, the fees are more affordable than Ethereum-based exchanges.
    Fast Transactions: Experience quick transaction speeds due to the efficiency of BSC.
    Yield Farming: Earn rewards by providing liquidity or participating in various farming pools.
    Conclusion
    PancakeSwap offers a user-friendly approach to trading cryptocurrencies, engaging users with its gamified elements like lotteries and collectibles. Whether you’re a beginner or an experienced trader, PancakeSwap provides an efficient and exciting way to dive into the world of decentralized finance. Always ensure to perform your due diligence before engaging in trading activities.

    For more detailed guides and support, visit the .

  25. Michaelkig表示:

    darknet websites darknet sites darknet markets

發佈留言

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