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

101,171 Responses

  1. JasonMasia表示:

    A fascinating story about Brazilian veteran Thiago Silva’s https://chelsea.thiago-silva.net difficult path to the top of European football as part of Chelsea London.

  2. Anthonyincut表示:

    The fascinating story of the phenomenal rise and meteoric fall of Diego Maradona https://napoli.diegomaradona.biz, who became a cult figure at Napoli in the 1980s.

  3. ThomasBeems表示:

    Rivaldo, or Rivaldo https://barcelona.rivaldo-br.com, is one of the greatest football players to ever play for Barcelona.

  4. смотреть русское порно худые смотреть русское порно худые .

  5. GabrielEpign表示:

    Преимущества аренды склада https://vyvozmusorascherbinka.ru/preimushhestva-arendy-sklada-kak-optimizirovat-biznes-proczessy-i-snizit-izderzhki/, как аренда складских помещений может улучшить ваш бизнес

  6. Anthonyfut表示:

    The story of Kanye West https://the-college-dropout.kanye-west-fr.com, starting with his debut album “The College Dropout,” which changed hip-hop and became his cultural legacy.

  7. BruceDor表示:

    Discover Rafael Nadal’s https://mls.inter-miami-fr.com impressive rise to the top of world tennis, from his debut to his career Grand Slam victory.

  8. DerrickKeS表示:

    Explore the career and significance of Monica Bellucci https://malena.monica-bellucci-fr.com in Malena (2000), which explores complex themes of beauty and human strength in wartime.

  9. MelvinHeick表示:

    Inter Miami FC https://mls.inter-miami-fr.com has become a major player in MLS thanks to its star roster, economic growth and international influence.

  10. Matthewbralt表示:

    Tyson Fury https://wbc.tyson-fury-fr.com is the undefeated WBC world champion and reigns supreme in boxing’s heavyweight division.

  11. Diplomi_rekl表示:

    куплю диплом рф куплю диплом рф .

  12. fus表示:

    The reliability of today’s football predictions on PredictZ varies, as they are based on statistical analysis and cannot guarantee outcomes. Past performance and match data inform these predictions. Are you ready for today’s football predictions? At Eagle Predict, we’ve got you covered with expert match predictions generated by our exceptional algorithm, boasting an impressive 80% accuracy overall. You can trust our algorithm to provide you with the best match predictions for today and every day. Focuspredict is the best football prediction site in the world. We offer reliable football predictions for today’s game and tomorrow’s game. We work hand in hand with our professional tipsters to make sure all our soccer predictions are accurate. Once you join us you will receive accurate football predictions from our professional tipsters to enable you to win your next game.
    https://lorenzolxgp766666.sharebyblog.com/27346224/best-nba-sports-bets-today
    The Bucks are 3-4 under Rivers. The team improved its defensive rating to 113.9, which is 11th. But its offense has lagged and the result is the total going under in five of these seven games. Milwaukee is still arguably a top-five team on the NBA standings. But this team is unreliable, especially for betting purposes. RotoWire provides millions of annual users with the latest fantasy sports, daily fantasy sports, and sports betting news, information, tools, and more. RotoWire provides real-time player news and notes across dozens of sports, as well. Once word of Antetokounmpo’s injury got out, the Pacers became the favorite in this series. After Lillard reminded everyone of what Dame Time can look like in the playoffs, the Bucks are solidly favored with their 1-0 series lead. Milwaukee is only a small favorite for Game 2 though because Giannis is not expected to return.

  13. Trefwev表示:

    Здравствуйте!
    Задумался а действительно можно купить диплом государственного образца в Москве, и был удивлен, все реально и главное официально!
    Сначала серфил в сети и искал такие темы как: купить диплом маляра, купить дипломы о высшем образовании цена, купить аттестат за 9 классов, купить диплом менеджера, купить диплом в владикавказе, получил базовую информацию.
    Остановился в итоге на материале купить диплом в перми, http://autoschool-progress.kz/index.php?subaction=userinfo&user=usefizaq
    Хорошей учебы!

  14. Diplomi_vmkl表示:

    купить диплом онлайн купить диплом онлайн .

  15. RobertHop表示:

    The new Premier League https://premier-league.chelsea-fr.com season has gotten off to an intriguing start, with a new-look Chelsea looking to return to the Champions League, but serious challenges lie ahead.

  16. Bobbyskymn表示:

    An exploration of the history of Turin’s https://turin.juventus-fr.org iconic football club – Juventus – its rivalries, success and influence on Italian football.

  17. BrianHoupt表示:

    The iconic Anfield https://enfield.liverpool-fr.com stadium and the passionate Liverpool fans are an integral part of English football culture.

  18. Diplomi_txPa表示:

    купить диплом медколледжа diplomasx.com .

  19. Eddiewesia表示:

    Единственная в России студия кастомных париков https://wigdealers.ru, где мастера индивидуально подбирают структуру волос и основу по форме головы, после чего стригут, окрашивают, делают укладку и доводят до идеала ваш будущий аксессуар.

  20. Diplomi_soei表示:

    сколько стоит диплом о среднем образовании ast-diploms.com .

  21. pharmacy表示:

    [url=https://nolvadexin.online/]where to buy tamoxifen[/url]

  22. kep表示:

    Software description provided by the publisher. Online board games provide much flexibility and deliver almost the same fun-filled experience with real humans (offline). Apply all tricks and strategies you know about playing checkers to beat the computer or your online opponent. At the start of the game, you should put all your focus on moving as many pieces as you can to the other side of the board to build a team of Kings. In Checkers, the player with more kinged pieces on the table is the one most likely to win the match, so it’s best to start early! The primary script that runs our games seems to not have loaded, somehow. Checkers, also known as Draughts, is a board game for two players. It is played in a square board, made of 64 smaller squares, with eight squares on each side.
    https://caidenbayw629639.losblogos.com/27310700/bts-uno-online
    If you have any input on ways we can improve, we would appreciate your feedback. Please email our corporate office at booking@huntsvilleescaperooms. Thanks! For more info on The Escape Game Nashville (Berry Hill) or things to do in the area, check out these articles. Keys, codes, and hidden objects all play a part in your quest to unlock the secrets of the rooms. You’ll need more than just intuition to progress – strategic thinking and a collaborative spirit are paramount if you hope to escape. So come explore the NYC Escape Room and Mystery Room NYC phenomena where the vibrant energy of performing in New York converges with the intrigue of an escape room game. Your next escape room adventure in the heart of NYC is beckoning. Are you ready to respond to the call and experience the best room escape that NY has to offer?

  23. Diplomi_hnet表示:

    купить дубликат диплома diplomyx.com .

  24. Diplomi_xxKn表示:

    купить диплом ссср в нижнем новгороде asxdiplomik.com .

  25. Uazruau表示:

    Привет, друзья!
    Заказать диплом любого ВУЗа
    Наша компания предлагает выгодно заказать диплом, который выполняется на оригинальной бумаге и заверен мокрыми печатями, водяными знаками, подписями должностных лиц. Наш диплом пройдет лубую проверку, даже с применением специально предназначенного оборудования. Решите свои задачи быстро и просто с нашей компанией.
    Где заказать диплом по актуальной специальности?
    https://kozhuhovo.forum2x2.ru/t6406-topic#13330
    Рады оказать помощь!.

  26. DavidGlito表示:

    Советую Mihaylov digital, их основная сфера это сео в Google и Yandex, а также разработка сайтов.

  27. Mitchelvom表示:

    Explore the rich history and unrivaled atmosphere of the iconic Old Trafford Stadium https://old-trafford.manchester-united-fr.com, home of one of the world’s most decorated football clubs, Manchester United.

  28. MarvinTer表示:

    How Taylor Swift https://midnights.taylor-swift-fr.com reinvented her sound and image on the intimate and reflective album “Midnights,” revealing new dimensions of her talent.

  29. WilliamVah表示:

    An exploration of Nicole Kidman’s https://watch.nicole-kidman-fr.com career, her notable roles, and her continued quest for excellence as an actress.

發佈留言

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