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

108,027 Responses

  1. EugeneZetry表示:

    You can now order your Spirit Halloween costume on Uber Eats
    кракен вход
    Uber is cashing in on spooky season.

    The ridehailing company will now deliver costumes, makeup, and even decorations from Spirit Halloween, the largest Halloween retailer in North America, Uber announced in a press release Friday.

    Big-box retailers are getting into Halloween earlier and earlier, suggesting American consumers continue spending on the October holiday even as they pull back from other discretionary purchases.

    Customers in the US and Canada can buy their Chipotle burrito costume for the same price as in store, but without having to visit the seasonal Halloween store that pops up in abandoned storefronts every year, Uber said. Of course, there will still be the fees associated with Uber Eats delivery.

    Spirit Halloween has 1,525 locations.

    “The holiday season officially kicks off this time of year, and households across the country are looking to on-demand delivery to get what’s needed—now,” said Beryl Sanders, director of US grocery and retail partnerships at Uber, in a statement.

    Since the pandemic, different types of retailers have partnered with Uber to deliver their goods – such as Olive Garden for its breadsticks and pasta. Uber Eats has also partnered with Big Lots, Lowe’s, Michael’s and Party City for on-demand delivery.

    Uber and its competitors have also experimented with robot deliveries, though those have not fully taken off in the US market.

  2. Patrickfeath表示:

    Automatic takeoffs are coming for passenger jets and they’re going to redraw the map of the sky
    kra9.cc

    In late 1965, at what’s now London Heathrow airport, a commercial flight coming from Paris made history by being the first to land automatically.

    The plane – A Trident 1C operated by BEA, which would later become British Airways – was equipped with a newly developed extension of the autopilot (a system to help guide the plane’s path without manual control) known as “autoland.”

    Today, automatic landing systems are installed on most commercial aircraft and improve the safety of landings in difficult weather or poor visibility.

    Now, nearly 60 years later, the world’s third largest aircraft manufacturer, Brazil’s Embraer, is introducing a similar technology, but for takeoffs.

    Called “E2 Enhanced Take Off System,” after the family of aircraft it’s designed for, the technology would not only improve safety by reducing pilot workload, but it would also improve range and takeoff weight, allowing the planes that use it to travel farther, according to Embraer.

    “The system is better than the pilots,” says Patrice London, principal performance engineer at Embraer, who has worked on the project for over a decade. ”That’s because it performs in the same way all the time. If you do 1,000 takeoffs, you will get 1,000 of exactly the same takeoff.”

    Embraer, London adds, has already started flight testing, with the aim to get it approved by aviation authorities in 2025, before introducing it from select airports.

  3. Kupit_bdPi表示:

    Заказать качественный бетон в Нижнем Новгороде, Широкий выбор бетонных смесей в Нижнем Новгороде, с доставкой на объект, Заказать качественный бетон у проверенных поставщиков в Нижнем Новгороде, Надежные бетонные заводы в Нижнем Новгороде, Заказать крупным оптом бетон в Нижнем Новгороде, по выгодной цене, Заказать качественный готовый бетон в Нижнем Новгороде, с доставкой
    купить бетон в нижнем новгороде https://1beton-52.ru/ .

  4. WallySWOPE表示:

    Look of the Week: Forget the naked dress, Kendall Jenner makes the case for underwear as outerwear
    kraken market

    On Monday, Kendall Jenner stepped out onto the L’Oreal Paris womenswear runway in a scarlet red Mugler gown that might have looked familiar to anyone with a sharp memory of 1999.

    The front of the dress was slashed open across Jenner’s right shoulder, exposing a matching denier bra. The peekaboo moment conjured up memories of another example of fashionable flashing: Lil’ Kim’s purple embellished jumpsuit at the VMAs 26 years earlier. On the red carpet, Kim’s left breast was almost entirely revealed by an asymmetrical cut — a mirror image of Jenner’s neckline — save for a matching purple nipple pasty.
    Jenner’s Mugler moment was just the latest example of a resurging tendency for underwear as outerwear. At the Nensi Dojaka runway show in London earlier this month, boxy blazers were shrugged over strappy bras while paneled bustiers in sheer fabric were paired with capri trousers and reimagined as going out tops. Brasseries were even left exposed to the elements at Erdem — a departure for a house beloved by both British acting royalty (Kristen Scott Thomas) and actual royalty (the Duchess of Cambridge). Dolce & Gabbana got the memo, too, showing satin corsets, garter belts and Madonna-esque cone bras at Milan Fashion Week on Saturday. Florence Pugh even wore one of the label’s risque designs in her first British Vogue cover last week — the circle neckline of her puff-shouldered black dress scooping just above the belly button, acting as a full-frontal frame for her bra.
    But the trend extends beyond just the runways. During the first performance of her “Short n’ Sweet” tour on Monday, singer Sabrina Carpenter took to the stage in a custom Victoria’s Secret bodysuit and stockings. Hand-adorned with over 150,000 crystals, the strapless pink lace-trimmed leotard took over 140 hours to make. On Monday,YouTube star and singer Jojo Siwa inverted the fad by donning a codpiece for a headline-grabbing cover shoot with LadyGunn magazine. The 15th century undergarment was bedazzled with flesh-colored gemstones.

  5. JeffreyDab表示:

    Look of the Week: Forget the naked dress, Kendall Jenner makes the case for underwear as outerwear
    kraken darknet

    On Monday, Kendall Jenner stepped out onto the L’Oreal Paris womenswear runway in a scarlet red Mugler gown that might have looked familiar to anyone with a sharp memory of 1999.

    The front of the dress was slashed open across Jenner’s right shoulder, exposing a matching denier bra. The peekaboo moment conjured up memories of another example of fashionable flashing: Lil’ Kim’s purple embellished jumpsuit at the VMAs 26 years earlier. On the red carpet, Kim’s left breast was almost entirely revealed by an asymmetrical cut — a mirror image of Jenner’s neckline — save for a matching purple nipple pasty.
    Jenner’s Mugler moment was just the latest example of a resurging tendency for underwear as outerwear. At the Nensi Dojaka runway show in London earlier this month, boxy blazers were shrugged over strappy bras while paneled bustiers in sheer fabric were paired with capri trousers and reimagined as going out tops. Brasseries were even left exposed to the elements at Erdem — a departure for a house beloved by both British acting royalty (Kristen Scott Thomas) and actual royalty (the Duchess of Cambridge). Dolce & Gabbana got the memo, too, showing satin corsets, garter belts and Madonna-esque cone bras at Milan Fashion Week on Saturday. Florence Pugh even wore one of the label’s risque designs in her first British Vogue cover last week — the circle neckline of her puff-shouldered black dress scooping just above the belly button, acting as a full-frontal frame for her bra.
    But the trend extends beyond just the runways. During the first performance of her “Short n’ Sweet” tour on Monday, singer Sabrina Carpenter took to the stage in a custom Victoria’s Secret bodysuit and stockings. Hand-adorned with over 150,000 crystals, the strapless pink lace-trimmed leotard took over 140 hours to make. On Monday,YouTube star and singer Jojo Siwa inverted the fad by donning a codpiece for a headline-grabbing cover shoot with LadyGunn magazine. The 15th century undergarment was bedazzled with flesh-colored gemstones.

  6. KeithMup表示:

    7 simple secrets to eating the Mediterranean way
    kraken onion
    What if “diet” wasn’t a dirty word?

    During Suzy Karadsheh’s childhood in Port Said, Egypt, diet culture was nonexistent.

    “My parents emphasized joy at the table, rather than anything else,” Karadsheh said. “I grew up with Mediterranean lifestyle principles that celebrate eating with the seasons, eating mostly whole foods and above all else, sharing.”

    But when Karadsheh moved to the United States at age 16, she witnessed people doing detoxes or restricting certain food groups or ingredients. Surrounded by that narrative and an abundance of new foods in her college dining hall, she says she “gained the freshman 31 instead of the freshman 15.” When she returned home to Egypt that summer, “I eased back into eating the Mediterranean food that I grew up with. During the span of about two months, I shed all of that weight without thinking I was ever on a diet.”
    To help invite joy back to the table for others — and to keep her family’s culinary heritage alive for her two daughters (now 14 and 22) — Atlanta-based Karadsheh launched The Mediterranean Dish food blog 10 years ago. Quickly, her table started getting filled with more than just her friends and family.

    “I started receiving emails from folks whose doctors had prescribed the Mediterranean diet and were seeking approachable recipes,” Karadsheh said. The plant-based eating lifestyle, often rated the world’s best diet, can reduce the risk for diabetes, high cholesterol, dementia, memory loss and depression, according to research. What’s more, the meal plan has been linked to stronger bones, a healthier heart and longer life.

    Preparing meals the Mediterranean way, according to Karadsheh, can help you “eat well and live joyfully. To us, ‘diet’ doesn’t mean a list of ‘eat this’ and ‘don’t eat that.’” Instead of omission, Karadsheh focuses on abundance, asking herself, “what can I add to my life through this way of living? More whole foods, vegetables, grains, legumes? Naturally, when you add these good-for-you ingredients, you eat less of what’s not as health-promoting,” she told CNN.

  7. Kupit_duPi表示:

    Бетон от надежного производителя в Нижнем Новгороде, быстро и выгодно, Бетон в Нижнем Новгороде: актуальные предложения, Бетон от надежных поставщиков в Нижнем Новгороде, Бетонные заводы в Нижнем Новгороде: широкий выбор, с доставкой на объект, по выгодной цене, Наилучший выбор готового бетона в Нижнем Новгороде, с высоким уровнем сервиса
    бетон купить в нижнем новгороде https://1beton-52.ru/ .

  8. сервисный центре предлагает ремонт телевизора – ремонт телевизора москва

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

  10. MichaelNok表示:

    You can now order your Spirit Halloween costume on Uber Eats
    Кракен тор
    Uber is cashing in on spooky season.

    The ridehailing company will now deliver costumes, makeup, and even decorations from Spirit Halloween, the largest Halloween retailer in North America, Uber announced in a press release Friday.

    Big-box retailers are getting into Halloween earlier and earlier, suggesting American consumers continue spending on the October holiday even as they pull back from other discretionary purchases.

    Customers in the US and Canada can buy their Chipotle burrito costume for the same price as in store, but without having to visit the seasonal Halloween store that pops up in abandoned storefronts every year, Uber said. Of course, there will still be the fees associated with Uber Eats delivery.

    Spirit Halloween has 1,525 locations.

    “The holiday season officially kicks off this time of year, and households across the country are looking to on-demand delivery to get what’s needed—now,” said Beryl Sanders, director of US grocery and retail partnerships at Uber, in a statement.

    Since the pandemic, different types of retailers have partnered with Uber to deliver their goods – such as Olive Garden for its breadsticks and pasta. Uber Eats has also partnered with Big Lots, Lowe’s, Michael’s and Party City for on-demand delivery.

    Uber and its competitors have also experimented with robot deliveries, though those have not fully taken off in the US market.

  11. JosephWrela表示:

    buy prednisone online fast shipping: 54 prednisone – prednisone 4 mg daily

  12. Gartandabsex表示:

    Как поднять настроение с помошью анекдота. Свежие картинки
    http://forum.south-park.ru/profile.php?mode=viewprofile&u=143630

  13. JosephWrela表示:

    Rybelsus 7mg: semaglutide – Rybelsus 7mg

  14. Davidmer表示:

    prednisone 5 mg tablet without a prescription: prednisone pharmacy prices – how to get prednisone without a prescription

  15. Jamielib表示:

  16. Davidmer表示:

    buy lasix online: lasix dosage – lasix dosage

  17. DouglasHoapy表示:

    1xBet
    Promo codes on 1xBet unlock bonuses like deposit matches, free bets, or free spins. These codes can be entered during registration or when making a deposit to claim the corresponding bonus.

  18. Arenda_wzka表示:

    Уникальные варианты аренды жилья на сутки|Забронируйте квартиру на сутки мечты|Уютные апартаменты с арендой на сутки|Резервируйте жилье на сутки онлайн|Эксклюзивные предложения аренды квартир на короткий срок|Идеальные квартиры на сутки для вашего отдыха|Привлекательные варианты аренды квартир на сутки|Выберите идеальное жилье на короткий срок|Выбирайте лучшие квартиры для короткого проживания|Идеальные варианты квартир на сутки для вашего отпуска|Бронируйте квартиры на сутки по выгодным ценам|Находите лучшие варианты жилья и бронируйте сейчас|Выберите лучшее жилье на короткое проживание|Лучшие апартаменты на сутки по доступной цене|Уникальные предложения аренды квартир на сутки|Бронирование квартир на сутки без комиссии|Идеальные варианты жилья на сутки для вашего отдыха|Привлекательные квартиры на сутки для вашего отпуска|Идеальные предложения аренды квартир на сутки|Уютные жилье на сутки по лучшим ценам
    квартиры гомель на сутки квартиры гомель на сутки .

  19. Arenda_saka表示:

    Уникальные варианты аренды жилья на сутки|Найдите свою идеальную квартиру на сутки|Лучшие варианты аренды квартир для вашего отдыха|Удобная система бронирования квартир на сутки|Выбор апартаментов на сутки по лучшим ценам|Удобные квартиры на сутки по доступной цене|Выбор жилья на короткий срок по вашему вкусу|Выберите идеальное жилье на короткий срок|Выбирайте лучшие квартиры для короткого проживания|Выберите комфортное жилье на короткий срок|Лучшие предложения аренды квартир на сутки|Идеальные предложения аренды жилья на сутки|Эксклюзивные варианты аренды квартир на сутки|Выбор квартир на короткий срок для вашего отдыха|Идеальные варианты жилья для вашего отдыха|Выбор апартаментов на короткий срок по лучшим ценам|Идеальные варианты жилья на сутки для вашего отдыха|Удобный поиск и бронирование апартаментов на сутки|Бронирование апартаментов на сутки с высоким уровнем сервиса|Выбор квартир на короткий срок для вашего отдыха
    квартиры на сутки в гомеле эконом класса квартиры на сутки в гомеле эконом класса .

  20. Davidmer表示:

    buy neurontin: neurontin 600 mg capsule – neurontin 100 mg tablets

  21. JosephFam表示:

    prednisone 10 mg canada: 400 mg prednisone – prednisone without prescription 10mg

  22. JosephWrela表示:

    lasix medication: cheap lasix – lasix 40mg

  23. JerryVam表示:

    Zooma

  24. JosephWrela表示:

    lasix dosage: cheap lasix – furosemida

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

  26. Arenda_nvka表示:

    Подборка самых выгодных предложений аренды квартиры на сутки|Забронируйте квартиру на сутки мечты|Квартиры на сутки в центре города|Простой способ аренды квартиры на короткий срок|Выбор апартаментов на сутки по лучшим ценам|Лучшие варианты аренды жилья на короткий срок|Идеальные апартаменты на сутки для вашего отпуска|Лучшее предложение аренды квартиры на сутки|Выбирайте лучшие квартиры для короткого проживания|Идеальные варианты квартир на сутки для вашего отпуска|Выбор апартаментов на короткий срок для вашего отдыха|Уютные квартиры на короткий срок для вашего отдыха|Удобный поиск и бронирование апартаментов на сутки|Лучшие апартаменты на сутки по доступной цене|Выбирайте комфортные апартаменты на короткий срок|Бронирование квартир на сутки без комиссии|Идеальные варианты жилья на сутки для вашего отдыха|Выбирайте лучшие варианты жилья на короткий срок|Выбор идеальных квартир для короткого проживания|Уютные жилье на сутки по лучшим ценам
    квартиры гомель посуточно квартиры гомель посуточно .

發佈留言

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