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還有很多好用的功能,可以到它官方的網站閱讀一些文章,基本上所有的數學運算應該都可以透過它來玩完成。
A brief history of sunglasses, from Ancient Rome to Hollywood
кракен онион
Sunglasses, or dark glasses, have always guarded against strong sunlight, but is there more to “shades” than we think?
The pupils of our eyes are delicate and react immediately to strong lights. Protecting them against light — even the brilliance reflected off snow — is important for everyone. Himalayan mountaineers wear goggles for this exact purpose.
Protection is partly the function of sunglasses. But dark or colored lens glasses have become fashion accessories and personal signature items. Think of the vast and famous collector of sunglasses Elton John, with his pink lensed heart-shaped extravaganzas and many others.
When did this interest in protecting the eyes begin, and at what point did dark glasses become a social statement as well as physical protection?
The Roman Emperor Nero is reported as holding polished gemstones to his eyes for sun protection as he watched fighting gladiators.
We know Canadian far north Copper Inuit and Alaskan Yupik wore snow goggles of many kinds made of antlers or whalebone and with tiny horizontal slits. Wearers looked through these and they were protected against the snow’s brilliant light when hunting. At the same time the very narrow eye holes helped them to focus on their prey.
In 12th-century China, judges wore sunglasses with smoked quartz lenses to hide their facial expressions — perhaps to retain their dignity or not convey emotions.
вывод из запоя круглосуточно ростов-на-дону вывод из запоя круглосуточно ростов-на-дону .
https://sweetbonanza25.com/# sweet bonanza oyna
Casino Siteleri: casino bahis siteleri – Casino Siteleri
Carrie Underwood slated to perform at Trump’s inauguration
kraken ссылка
Country music star Carrie Underwood is slated to perform “America the Beautiful” at President-elect Donald Trump’s inauguration, according to a copy of the program obtained by CNN and confirmed by a spokesperson for the inaugural committee.
“I love our country and am honored to have been asked to sing at the Inauguration and to be a small part of this historic event,” Underwood said in a statement to CNN. “I am humbled to answer the call at a time when we must all come together in the spirit of unity and looking to the future.”
The presidential oath of office will be administered by Supreme Court Chief Justice John Roberts with Justice Brett Kavanaugh expected to administer the oath of office to Vice President-elect JD Vance.
Trump’s inauguration as the 47th president of the United States will take place on January 20 at the US Capitol.
Underwood is a big get for Trump’s inauguration, considering Hollywood’s Trump blackout over the course of his political career.
In his first term and throughout the past three elections, Trump has struggled to garner support from major Hollywood stars. At the Republican National Convention last year, the two biggest stars onstage with Trump were musician Kid Rock and retired WWE wrestler Hulk Hogan – a far cry from a superstar at the height of their career, like Underwood.
The Grammy-winning artist is as high-profile as you can get in country music, not only with numerous platinum hits, but also with public-facing, mainstream business associations. Underwood is the face of Sunday Night Football and is set to make her debut this March as a judge on ABC’s “American Idol” – the singing competition show that catapulted her to fame when she won in 2005.
While many NFL fans will likely applaud Underwood for singing at the inauguration, any time a celebrity aligns themselves with Trump, they run the risk of alienating left-leaning fans and Hollywood allies.
Underwood has kept her politics under wraps over the course of her career. In her statement, she did not mention Trump by name and kept her focus on unifying the country – still, Underwood’s decision to publicly align with Trump is a big statement for any star, particularly one as private as the singer.
Historically, Hollywood has always been closely associated with the Democratic Party, but country stars have always been an outlier, leaning more conservative. In recent years, as new singers join the genre, country music has gotten to be more progressive. This past election cycle, country stars like Mickey Guyton and Maren Morris stood with Vice President Kamala Harris.
Бесплатное программное обеспечение для видеонаблюдения на ПК для распознавания лиц поддерживает все типы IP камер. Это комплексное решение, включающее VMS и CMS, позволяет записывать и просматривать RTSP-видеопотоки, а также управлять большим количеством IP-камер с единой платформы. Встроена видеоаналитика на основе ИИ, которая обнаруживает объекты в кадре, распознает автомобильные номера и лица, а также выявляет признаки дыма и огня.
программа для просмотра видео с камер наблюдения
A brief history of sunglasses, from Ancient Rome to Hollywood
kraken тор браузер
Sunglasses, or dark glasses, have always guarded against strong sunlight, but is there more to “shades” than we think?
The pupils of our eyes are delicate and react immediately to strong lights. Protecting them against light — even the brilliance reflected off snow — is important for everyone. Himalayan mountaineers wear goggles for this exact purpose.
Protection is partly the function of sunglasses. But dark or colored lens glasses have become fashion accessories and personal signature items. Think of the vast and famous collector of sunglasses Elton John, with his pink lensed heart-shaped extravaganzas and many others.
When did this interest in protecting the eyes begin, and at what point did dark glasses become a social statement as well as physical protection?
The Roman Emperor Nero is reported as holding polished gemstones to his eyes for sun protection as he watched fighting gladiators.
We know Canadian far north Copper Inuit and Alaskan Yupik wore snow goggles of many kinds made of antlers or whalebone and with tiny horizontal slits. Wearers looked through these and they were protected against the snow’s brilliant light when hunting. At the same time the very narrow eye holes helped them to focus on their prey.
In 12th-century China, judges wore sunglasses with smoked quartz lenses to hide their facial expressions — perhaps to retain their dignity or not convey emotions.
вывод из запоя на дому ростов-на-дону https://vyvod-iz-zapoya-rostov27.ru .
вывод из запоя цены ростов вывод из запоя цены ростов .
Canl? Casino Siteleri: en guvenilir casino siteleri – lisanslД± kumar siteleri
amoxicillin buy online – buy valsartan 160mg without prescription purchase ipratropium sale
Carrie Underwood slated to perform at Trump’s inauguration
kraken ссылка
Country music star Carrie Underwood is slated to perform “America the Beautiful” at President-elect Donald Trump’s inauguration, according to a copy of the program obtained by CNN and confirmed by a spokesperson for the inaugural committee.
“I love our country and am honored to have been asked to sing at the Inauguration and to be a small part of this historic event,” Underwood said in a statement to CNN. “I am humbled to answer the call at a time when we must all come together in the spirit of unity and looking to the future.”
The presidential oath of office will be administered by Supreme Court Chief Justice John Roberts with Justice Brett Kavanaugh expected to administer the oath of office to Vice President-elect JD Vance.
Trump’s inauguration as the 47th president of the United States will take place on January 20 at the US Capitol.
Underwood is a big get for Trump’s inauguration, considering Hollywood’s Trump blackout over the course of his political career.
In his first term and throughout the past three elections, Trump has struggled to garner support from major Hollywood stars. At the Republican National Convention last year, the two biggest stars onstage with Trump were musician Kid Rock and retired WWE wrestler Hulk Hogan – a far cry from a superstar at the height of their career, like Underwood.
The Grammy-winning artist is as high-profile as you can get in country music, not only with numerous platinum hits, but also with public-facing, mainstream business associations. Underwood is the face of Sunday Night Football and is set to make her debut this March as a judge on ABC’s “American Idol” – the singing competition show that catapulted her to fame when she won in 2005.
While many NFL fans will likely applaud Underwood for singing at the inauguration, any time a celebrity aligns themselves with Trump, they run the risk of alienating left-leaning fans and Hollywood allies.
Underwood has kept her politics under wraps over the course of her career. In her statement, she did not mention Trump by name and kept her focus on unifying the country – still, Underwood’s decision to publicly align with Trump is a big statement for any star, particularly one as private as the singer.
Historically, Hollywood has always been closely associated with the Democratic Party, but country stars have always been an outlier, leaning more conservative. In recent years, as new singers join the genre, country music has gotten to be more progressive. This past election cycle, country stars like Mickey Guyton and Maren Morris stood with Vice President Kamala Harris.
sweet bonanza guncel: sweet bonanza giris – sweet bonanza slot
A brief history of sunglasses, from Ancient Rome to Hollywood
Кракен даркнет
Sunglasses, or dark glasses, have always guarded against strong sunlight, but is there more to “shades” than we think?
The pupils of our eyes are delicate and react immediately to strong lights. Protecting them against light — even the brilliance reflected off snow — is important for everyone. Himalayan mountaineers wear goggles for this exact purpose.
Protection is partly the function of sunglasses. But dark or colored lens glasses have become fashion accessories and personal signature items. Think of the vast and famous collector of sunglasses Elton John, with his pink lensed heart-shaped extravaganzas and many others.
When did this interest in protecting the eyes begin, and at what point did dark glasses become a social statement as well as physical protection?
The Roman Emperor Nero is reported as holding polished gemstones to his eyes for sun protection as he watched fighting gladiators.
We know Canadian far north Copper Inuit and Alaskan Yupik wore snow goggles of many kinds made of antlers or whalebone and with tiny horizontal slits. Wearers looked through these and they were protected against the snow’s brilliant light when hunting. At the same time the very narrow eye holes helped them to focus on their prey.
In 12th-century China, judges wore sunglasses with smoked quartz lenses to hide their facial expressions — perhaps to retain their dignity or not convey emotions.
kometa casino
When you have great content material to share on your weblog, why not repurpose it into video content material?
I doubt that I’ll do enterprise with Quinn’s once more.
https://slotsiteleri25.com/# slot oyunlar? puf noktalar?
http://casinositeleri25.com/# canl? casino siteleri
https://slotsiteleri25.com/# en cok kazand?ran slot oyunlar?
This is essential to optimizing a sustainable market cap.
deneme bonusu veren yeni siteler deneme bonusu veren siteler yat?r?ms?z deneme bonusu veren siteler
https://casinositeleri25.com/# Deneme Bonusu Veren Siteler
az parayla cok kazandiran slot oyunlar? slot siteleri guvenilir slot siteleri
вывод из запоя в ростове-на-дону вывод из запоя в ростове-на-дону .
Find Out More https://glassartistsfellowship.com/2024/06/13/garansi-kekalahan-100-rahasia-di-balik-mesin-slot-yang-menghancurkan-harapan/
en cok kazand?ran slot oyunlar? az parayla cok kazandiran slot oyunlar? en cok kazand?ran slot oyunlar?
Разнообразие фурнитуры для плинтуса, найдите идеальный вариант.
Прочные материалы для плинтуса, долговечные и надежные в использовании.
Удобство монтажа фурнитуры для плинтуса, сэкономьте время и силы.
Тренды в дизайне фурнитуры для плинтуса, сделайте дом уютным и стильным.
Эко-варианты элементов для плинтуса, для заботы об окружающей среде.
Популярные цветовые решения для фурнитуры плинтуса, создайте гармонию в доме.
Уникальные элементы для стильного плинтуса, выразите свою индивидуальность через дизайн.
Советы по выбору фурнитуры для плинтуса, для долгосрочного использования.
Стильные детали для украшения плинтуса, добавьте шарм вашему интерьеру.
Фурнитура для плинтуса в классическом стиле, подчеркните изысканный вкус в дизайне.
сайт каталог товаров сайт каталог товаров .
We are able to examine it to a top cyclist on a modern bicycle who will try to go at maximum pace within the lightest (lowest) gear.
нарколог вывод из запоя нарколог вывод из запоя .