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

  1. TracyRak表示:

    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.me and transform your body now!

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

  3. Dwayneseisa表示:

    Tadalafil Tablet cialis without a doctor prescription Tadalafil Easy Buy

  4. Jamesavata表示:

    пин ап вход – pinup 2025

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

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

  7. Dwayneseisa表示:

    Generic 100mg Easy Generic100mgEasy Viagra online price

  8. CharlesGaP表示:

    Aged 15, New Zealander Sam Ruthe has already run a four-minute mile. He would ‘love to try and qualify’ for the 2028 Olympics
    paraswap

    Sam Ruthe had the eyes of thousands on him when he stepped onto a running track in Auckland just over a week ago.

    Undaunted by the occasion, Ruthe went on to become the first 15-year-old to run a sub-four-minute mile, even managing a nonchalant shrug of the shoulders as he crossed the finish line.

    The race was almost entirely engineered for the high school student to break the fabled four-minute barrier – a feat first achieved by Roger Bannister more than 70 years ago – but the weight of running history was a burden that Ruthe seemed to bear lightly.

    The first three laps, he later said in a video documenting the race, “felt pretty comfortable – nothing too crazy.”

    Perhaps the most intimidating part of his achievement occurred when Ruthe returned to school the next day, only to be immediately called into the principal’s office.

    “He’s like, ‘Alright, so you’re gonna have to go up on stage and we’ll get the whole school to clap you,’” Ruthe tells CNN Sports’ Patrick Snell. “It was really scary, actually. I headed into class and everyone thought I was famous.”

    It’s easy to forget, given his history-making performance last week, that Ruthe is like most other 15-year-olds in New Zealand. He goes to school, spends time with his friends, and helps with chores around the house.

    He also just happens to be one of the most exciting middle-distance runners on the planet, one of the latest star athletes to emerge from sports-mad New Zealand.

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

  10. HowardSek表示:

    Tyler O’Neill hits record-extending sixth straight Opening Day home run
    orbiter
    For six seasons in a row, Tyler O’Neill has homered on MLB Opening Day.

    Making his debut for the Baltimore Orioles on Thursday, O’Neill started the season with his record-extending sixth straight home run on Opening Day during his team’s 12-2 win against the Toronto Blue Jays.

    No other player has homered on more than four consecutive Opening Days, with the 29-year-old outfielder’s three-run shot sending the Orioles into a 5-0 lead at the top of the third at Rogers Centre.
    Todd Hundley (1994-97), Gary Carter (1977-80) and Yogi Berra (1955-58) all hit four consecutive home runs on Opening Day, while the Major League Baseball record for the total number of Opening Day home runs is held jointly by Adam Dunn, Ken Griffey Jr. and Frank Robinson on eight.

    “I’m just not trying to make too much of it,” O’Neill told reporters about his streak. “I’m just trying to go out, have a good first at-bat and see what the game gives me from there.

    “Obviously, I understand what’s going on, but it’s not like I’m going out there trying to do anything crazy.”

    O’Neill, who signed a three-year, $49.5 million contract to join Baltimore from the Boston Red Sox in the offseason, finished three-for-three with three RBIs and two walks against the Blue Jays.

    “It’s a little different when the lights turn on and you’ve got to show up, so it was really cool to see all the guys show up today,” he said. “We got after it out there.”

    While the first two games of the MLB regular season took place between the Chicago Cubs and Los Angeles Dodgers in Tokyo last week, Thursday marked the first official day of the season in the United States.

  11. Jamesavata表示:

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

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

  13. Jamesavata表示:

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

  14. Robertror表示:

    Look of the Week: Naomi Watts is twinning with her canine co-star
    orbiter finance
    What’s white and black and red all over? Naomi Watts and her 145lb co-star, Bing, a Great Dane, taking a dog walk on the crimson carpet for the New York premiere of “The Friend.”

    Directed by Scott Mcgehee and adapted from Sigrid Nunez’s 2018 novel of the same name, the film — set to release in US theaters on March 28 and in the UK on April 25 — follows a solitary writer and teacher named Iris whose life is upended after a close friend bequeaths his giant pet dog to her following his death.

    In front of the cameras Monday evening, the “Mulholland Drive” actor and Bing looked like they were cut from the same cloth — both in temperament and in their matching black polka dots. Watts was dressed in a white gown with fur-tufted spots that bore a striking resemblance to Bing’s own coat, but the Cruella de Vil comparisons ended there. Instead, Watts and Bing were captured in the throes of lots of paw-shakes, puppy kisses and head scratches.
    The dress that Watts wore, titled the “Domino” and designed by Jacquemus, debuted during the Spring-Summer 2025 Paris couture shows in January. The look was both elegant and offbeat, with a high-cowl neck and open-back, asymmetrical waistline that mimicked a French tuck. It was styled with a skirt that sprouted furry black polka dots, which close up were unnervingly reminiscent of body hair. But from afar they gave the impression of soft-edged dabs of watercolor bleeding downstream.

    The look was styled by Jeanann Williams, who has also been working with “The White Lotus” star Leslie Bibb. Williams’ decision to coordinate Watts with Bing was a new take on method dressing — the thematic styling trend that has dominated celebrity red carpets since Greta Gerwig’s “Barbie” in 2023. Since then, the sartorial trope, which connects actors to their on-screen characters through clothes, has become somewhat tired — with some observers claiming that the 7-month-long “Wicked” press tour, in which Cynthia Erivo and Ariana Grande became prisoners to the colors green and pink, was peak saturation.

  15. JesseDex表示:

    пин ап: https://pinupkz.life/

  16. JesseDex表示:

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

  17. Dwayneseisa表示:

    Buy Tadalafil 10mg TadalafilEasyBuy.com Tadalafil Easy Buy

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

  19. ByronShusa表示:

    Critics say this power imbalance is clear in the 2016 contract Guyana signed with Exxon. Under the agreement, Exxon keeps 75% of everything it makes from its oil operations in Guyana, with the remaining 25% shared equally between the company and the government, which also takes a 2% royalty.
    lido fi
    “It was a bad deal,” Ali said in the BBC interview, but he has rejected the idea of unilaterally changing the agreement, which was signed by the previous government. He says the next contract with Exxon will be on different terms.

    An Exxon spokesperson said the contract is “globally competitive for countries at a similar stage of exploration” and said Guyana is averaging $1 billion a year in “oil profits.”

    Exxon has also faced a number of lawsuits over its potential environmental impact, many filed by Melinda Janki, a Guyanese international lawyer, who drafted the country’s Environmental Protection Act back in the 1990s.

    A big victory for Guyana’s people and environment came in 2023, when the court ruled Exxon should have unlimited liability for the costs of any oil spill. Exxon has since appealed the ruling and has posted a $2 billion guarantee while it awaits the appeal outcome.
    Exxon said this commitment supplements “its robust balance sheets … and the insurance policies they already had in place.” Janki says this isn’t enough. Offshore oil spills can be extremely expensive to deal with, the 2010 Deepwater Horizon spill cost nearly $70 billion to clean up.

    The push and pull between those who say oil offers Guyana a brighter future and those who fear the industry’s impact will continue.

    Exxon said it’s had a positive impact on the country, including employing more than 6,200 people, investing more than $2 billion with local Guyanese businesses since 2015 and spending more than $43 million on community projects.

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

  21. Dwayneseisa表示:

    Generic 100mg Easy best price for viagra 100mg Generic 100mg Easy

  22. HerbertDrilk表示:

    A tiny rainforest country is growing into a petrostate. A US oil company could reap the biggest rewards
    swell network
    Guyana’s destiny changed in 2015. US fossil fuel giant Exxon discovered nearly 11 billion barrels of oil in the deep water off the coast of this tiny, rainforested country.

    It was one of the most spectacular oil discoveries of recent decades. By 2019, Exxon and its partners, US oil company Hess and China-headquartered CNOOC, had started producing the fossil fuel.? They now pump around 650,000 barrels of oil a day, with plans to more than double this to 1.3 million by 2027.

    Guyana now has the world’s highest expected oil production growth through 2035.

    This country — sandwiched between Brazil, Venezuela and Suriname — has been hailed as a climate champion for the lush, well-preserved forests that carpet nearly 90% of its land. It is on the path to becoming a petrostate at the same time as the impacts of the fossil fuel-driven climate crisis escalate.

    While the government says environmental protection and an oil industry can go hand-in-hand, and low-income countries must be allowed to exploit their own resources, critics say it’s a dangerous path in a warming world, and the benefits may ultimately skew toward Exxon — not Guyana.

  23. Billynot表示:

    Mist and microlightning
    solflare wallet
    To recreate a scenario that may have produced Earth’s first organic molecules, researchers built upon experiments from 1953 when American chemists Stanley Miller and Harold Urey concocted a gas mixture mimicking the atmosphere of ancient Earth. Miller and Urey combined ammonia (NH3), methane (CH4), hydrogen (H2) and water, enclosed their “atmosphere” inside a glass sphere and jolted it with electricity, producing simple amino acids containing carbon and nitrogen. The Miller-Urey experiment, as it is now known, supported the scientific theory of abiogenesis: that life could emerge from nonliving molecules.
    For the new study, scientists revisited the 1953 experiments but directed their attention toward electrical activity on a smaller scale, said senior study author Dr. Richard Zare, the Marguerite Blake Wilbur Professor of Natural Science and professor of chemistry at Stanford University in California. Zare and his colleagues looked at electricity exchange between charged water droplets measuring between 1 micron and 20 microns in diameter. (The width of a human hair is 100 microns.)

    “The big droplets are positively charged. The little droplets are negatively charged,” Zare told CNN. “When droplets that have opposite charges are close together, electrons can jump from the negatively charged droplet to the positively charged droplet.”
    The researchers mixed ammonia, carbon dioxide, methane and nitrogen in a glass bulb, then sprayed the gases with water mist, using a high-speed camera to capture faint flashes of microlightning in the vapor. When they examined the bulb’s contents, they found organic molecules with carbon-nitrogen bonds. These included the amino acid glycine and uracil, a nucleotide base in RNA.

    “We discovered no new chemistry; we have actually reproduced all the chemistry that Miller and Urey did in 1953,” Zare said. Nor did the team discover new physics, he added — the experiments were based on known principles of electrostatics.

    “What we have done, for the first time, is we have seen that little droplets, when they’re formed from water, actually emit light and get this spark,” Zare said. “That’s new. And that spark causes all types of chemical transformations.”

  24. Jamesavata表示:

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

  25. uxqmggzlk表示:

    Crash X: Crash X is another similar game to JetX, where you bet on a rocket that flies higher and higher, while the multiplier increases. The rocket can crash at any moment, and you have to cash out before that happens. Crash X game is developed by BGaming, and you can play it at some of the best online casinos in India, such as BitStarz, 7Bit Casino, and mBit Casino. The experience of playing Jet X bet in India is shaped by its innovative gameplay, accessible mechanics, and the potential for substantial rewards. It has quickly become a popular choice among Indian players, offering something different from the usual online casino fare. Its blend of chance and strategy attracts a wide range of players, from beginners to experienced veterans. As the online gaming market continues to expand in India, the JetX bet is well-positioned to maintain its momentum, attracting a growing number of enthusiasts looking for a fresh and exciting challenge.
    https://decidim.rezero.cat/profiles/weitosuse1979/activity
    Our analysis of this game showed that the risks associated with hacking Spribe Mines hack are significant from both a legal and security perspective. Respinix is an independent platform offering visitors access to free demo versions of online slots. All information on Respinix is provided for informational and entertainment purposes only. Respinix does not offer any real money gambling game. Always there to help you, no matter the time zone.  Open 24 Hours Visit Us Today! Before diving into the details, it’s important to note that the Mines Bet hack comes with considerable risks, both legal and in-game. If you’re curious about how this Mines hack works, read on to find out more. One of the best things about the Mines game is its perfect blend of strategy and unpredictability. While players may set their difficulty level by adjusting the amount of mines, each tile reveal keeps the game interesting. Moreover, when you’re ready to step up your game, the switch from the Mines demo to real money play is both smooth and enticing.

  26. Dwayneseisa表示:

    Sildenafil 100mg price buy generic 100mg viagra online Generic 100mg Easy

  27. Williamuniot表示:

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

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

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

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